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

class UNODOCK_Admin {

	private $page_hook;

	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_ajax_udock_save_settings', array( $this, 'ajax_save_settings' ) );
		add_action( 'wp_ajax_udock_clear_cache', array( $this, 'ajax_clear_cache' ) );
		add_filter( 'plugin_row_meta', array( $this, 'add_row_meta_links' ), 10, 2 );
		add_filter( 'plugin_action_links_' . UNODOCK_BASENAME, array( $this, 'add_action_links' ) );
		add_action( 'admin_notices', array( $this, 'maybe_render_review_notice' ) );
		add_action( 'admin_post_udock_review_action', array( $this, 'handle_review_action' ) );
	}

	/**
	 * Whether the "please rate us" notice should be shown: free tier only,
	 * at least 3 days after install, not permanently dismissed, and not
	 * currently snoozed via "Maybe later".
	 */
	private function should_show_review_notice() {
		if ( udock_is_pro() ) {
			return false;
		}
		if ( 'yes' === get_option( 'udock_review_dismissed' ) ) {
			return false;
		}

		$installed_at = get_option( 'udock_installed_at' );
		if ( ! $installed_at || ( time() - (int) $installed_at ) < 3 * DAY_IN_SECONDS ) {
			return false;
		}

		$snooze_until = (int) get_option( 'udock_review_snooze_until', 0 );
		if ( $snooze_until && time() < $snooze_until ) {
			return false;
		}

		return true;
	}

	public function maybe_render_review_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! $this->should_show_review_notice() ) {
			return;
		}

		$base_url = admin_url( 'admin-post.php' );

		$review_url  = wp_nonce_url( add_query_arg( array( 'action' => 'udock_review_action', 'choice' => 'review' ), $base_url ), 'udock_review_action' );
		$did_url     = wp_nonce_url( add_query_arg( array( 'action' => 'udock_review_action', 'choice' => 'already_did' ), $base_url ), 'udock_review_action' );
		$later_url   = wp_nonce_url( add_query_arg( array( 'action' => 'udock_review_action', 'choice' => 'later' ), $base_url ), 'udock_review_action' );
		?>
		<div class="notice notice-info udock-review-notice">
			<p>
				<strong>UnoDock</strong> —
				<?php esc_html_e( 'We hope you are liking UnoDock. Please rate this awesome plugin :) because you are awesome as well.', 'unodock' ); ?>
			</p>
			<p>
				<a href="<?php echo esc_url( $review_url ); ?>" class="button button-primary" style="margin-right:8px;"><?php esc_html_e( 'Leave a review', 'unodock' ); ?></a>
				<a href="<?php echo esc_url( $did_url ); ?>" class="button" style="margin-right:8px;"><?php esc_html_e( 'Already did', 'unodock' ); ?></a>
				<a href="<?php echo esc_url( $later_url ); ?>" class="button"><?php esc_html_e( 'Maybe later', 'unodock' ); ?></a>
			</p>
		</div>
		<?php
	}

	public function handle_review_action() {
		check_admin_referer( 'udock_review_action' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized.', 'unodock' ) );
		}

		$choice = isset( $_GET['choice'] ) ? sanitize_key( $_GET['choice'] ) : '';

		if ( in_array( $choice, array( 'review', 'already_did' ), true ) ) {
			update_option( 'udock_review_dismissed', 'yes' );
			delete_option( 'udock_review_snooze_until' );
		} elseif ( 'later' === $choice ) {
			update_option( 'udock_review_snooze_until', time() + 3 * DAY_IN_SECONDS );
		}

		if ( 'review' === $choice ) {
			// TODO: replace with the real WordPress.org reviews URL once the plugin is published.
			wp_safe_redirect( 'https://wordpress.org/support/plugin/unodock/reviews/#new-post' );
			exit;
		}

		wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url() );
		exit;
	}

	/**
	 * Adds a "Settings" link next to Activate/Deactivate on the plugins list,
	 * and replaces the auto-generated "Visit plugin site" link with "Docs".
	 */
	public function add_action_links( $links ) {
		$settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=unodock' ) ) . '">' . esc_html__( 'Settings', 'unodock' ) . '</a>';
		array_unshift( $links, $settings_link );
		return $links;
	}

	/**
	 * Adds a "Plugin page" link on the UnoDock row, and replaces the
	 * auto-generated "Visit plugin site" link (from the Plugin URI header)
	 * with a direct link to the documentation.
	 */
	public function add_row_meta_links( $links, $plugin_file ) {
		if ( UNODOCK_BASENAME !== $plugin_file ) {
			return $links;
		}

		foreach ( $links as $index => $link ) {
			if ( false !== strpos( $link, 'Visit plugin site' ) ) {
				$links[ $index ] = '<a href="' . esc_url( 'https://unoizestudio.com/doc-unodock' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Docs', 'unodock' ) . '</a>';
			}
		}

		$links[] = '<a href="' . esc_url( 'https://unoizestudio.com/unodock' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Plugin page', 'unodock' ) . '</a>';

		return $links;
	}

	public function register_menu() {
		$this->page_hook = add_menu_page(
			__( 'UnoDock', 'unodock' ),
			__( 'UnoDock', 'unodock' ),
			'manage_options',
			'unodock',
			array( $this, 'render_page' ),
			$this->get_menu_icon(),
			59 // sits below Elementor in most installs
		);
	}

	/**
	 * Builds the base64 SVG data URI WordPress expects for a custom
	 * admin menu icon (it recolors it automatically to match the
	 * current admin color scheme).
	 */
	private function get_menu_icon() {
		$svg_path = UNODOCK_PATH . 'assets/images/unodock-dashicon.svg';

		if ( ! file_exists( $svg_path ) ) {
			return 'dashicons-align-center';
		}

		$svg = file_get_contents( $svg_path );
		return 'data:image/svg+xml;base64,' . base64_encode( $svg );
	}

	public function enqueue_assets( $hook ) {
		if ( $hook !== $this->page_hook ) {
			return;
		}

		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_script( 'jquery-ui-sortable' );

		wp_enqueue_style(
			'udock-icons',
			UNODOCK_URL . 'assets/css/unodock-icons.css',
			array(),
			udock_asset_version( 'assets/css/unodock-icons.css' )
		);

		wp_enqueue_style(
			'udock-admin',
			UNODOCK_URL . 'assets/css/admin.css',
			array( 'udock-icons' ),
			udock_asset_version( 'assets/css/admin.css' )
		);

		wp_enqueue_script(
			'udock-admin',
			UNODOCK_URL . 'assets/js/admin.js',
			array( 'jquery', 'wp-color-picker', 'jquery-ui-sortable' ),
			udock_asset_version( 'assets/js/admin.js' ),
			true
		);

		wp_localize_script( 'udock-admin', 'UNODOCK_DATA', array(
			'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
			'nonce'            => wp_create_nonce( 'udock_save_settings' ),
			'clearCacheNonce'  => wp_create_nonce( 'udock_clear_cache' ),
			'settings'         => UNODOCK_Settings::get_settings(),
			'iconCategories'   => UNODOCK_Icons::get_categories(),
			'pages'            => UNODOCK_Settings::get_pages_for_select(),
			'templates'        => UNODOCK_Settings::get_templates(),
			'maxButtons'       => udock_max_buttons(),
			'isPremium'        => udock_is_pro(),
			'upgradeUrl'       => ( function_exists( 'unodock_fs' ) && unodock_fs() ) ? unodock_fs()->get_upgrade_url() : 'https://unoizestudio.com/unodock-pro',
			'wooCommerceActive'=> class_exists( 'WooCommerce' ),
			'i18n'             => array(
				'saved'          => __( 'Settings saved successfully!', 'unodock' ),
				'error'          => __( 'Something went wrong while saving. Please try again.', 'unodock' ),
				'confirmDel'     => __( 'Remove this button?', 'unodock' ),
				'maxReached'     => __( 'Free plan limit reached (4 buttons). Upgrade to UnoDock PRO to add up to 6.', 'unodock' ),
				'maxReachedPro'  => __( 'You\'ve reached the maximum of 6 buttons.', 'unodock' ),
				'newButton'      => __( 'New button', 'unodock' ),
				'cacheCleared'   => __( 'Cache cleared successfully!', 'unodock' ),
				'cacheError'     => __( 'Something went wrong while clearing the cache.', 'unodock' ),
				'confirmCache'   => __( 'This clears internal UnoDock data (old/orphaned entries). Your current settings are kept. Continue?', 'unodock' ),
				'confirmTemplate'=> __( 'This replaces your current buttons and appearance settings with this template. Continue?', 'unodock' ),
				'templateApplied'=> __( 'Template applied! Remember to save your changes.', 'unodock' ),
				'proRequired'    => __( 'This is a PRO feature. Upgrade to UnoDock PRO to unlock it.', 'unodock' ),
				'proTemplate'    => __( 'This template is part of UnoDock PRO. Upgrade to unlock it.', 'unodock' ),
			),
		) );
	}

	public function ajax_save_settings() {
		check_ajax_referer( 'udock_save_settings', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'unauthorized' ), 403 );
		}

		// The raw payload is a JSON blob representing the full settings
		// structure; it can't be run through a text sanitizer without
		// corrupting the JSON. It's nonce-protected, capability-checked
		// above, and every individual field is strictly validated and
		// sanitized by type in UNODOCK_Settings::save_settings() right
		// after being decoded, so this is safe.
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$payload = isset( $_POST['payload'] ) ? wp_unslash( $_POST['payload'] ) : '';
		$data    = json_decode( $payload, true );

		if ( ! is_array( $data ) ) {
			wp_send_json_error( array( 'message' => 'invalid_payload' ), 400 );
		}

		$saved = UNODOCK_Settings::save_settings( $data );

		wp_send_json_success( array( 'settings' => $saved ) );
	}

	/**
	 * Clears internal UnoDock data: leftover/orphaned options from earlier
	 * plugin versions, and any transients used internally (e.g. cached
	 * WooCommerce cart counts). The current saved settings are kept.
	 */
	public function ajax_clear_cache() {
		check_ajax_referer( 'udock_clear_cache', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'unauthorized' ), 403 );
		}

		global $wpdb;

		// Remove orphaned options left over from earlier plugin names/versions.
		delete_option( 'mnp_settings' );

		// Remove any transients created by UnoDock.
		// A direct query is necessary here: there is no core WordPress API
		// for deleting transients by name pattern (only by exact name), and
		// the "no caching" suggestion doesn't apply to a DELETE statement.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				$wpdb->esc_like( '_transient_udock_' ) . '%',
				$wpdb->esc_like( '_transient_timeout_udock_' ) . '%'
			)
		);

		wp_send_json_success();
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		include UNODOCK_PATH . 'includes/admin-page.php';
	}
}
