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

class Aegisify_Dashboard_News_Widget {

	const WIDGET_ID = 'aegisify_dashboard_news_widget';

	public static function init(): void {
		if ( ! is_admin() ) {
			return;
		}

		add_action( 'wp_dashboard_setup', array( __CLASS__, 'register_widget' ) );

		// Force our widget to be first in the saved per-user dashboard order.
		add_filter( 'get_user_option_meta-box-order_dashboard', array( __CLASS__, 'filter_dashboard_order' ), 99 );
	}

	public static function register_widget(): void {
		wp_add_dashboard_widget(
			self::WIDGET_ID,
			esc_html__( 'Aegisify News & Updates', 'aegisify' ),
			array( __CLASS__, 'render_widget' )
		);

		self::move_widget_to_top();
	}
	private static function move_widget_to_top(): void {
		global $wp_meta_boxes;

		if ( ! isset( $wp_meta_boxes['dashboard']['normal']['core'][ self::WIDGET_ID ] ) ) {
			return;
		}

		if ( ! isset( $wp_meta_boxes['dashboard']['side']['core'] ) || ! is_array( $wp_meta_boxes['dashboard']['side']['core'] ) ) {
			$wp_meta_boxes['dashboard']['side']['core'] = array();
		}

		$normal_core_widgets = $wp_meta_boxes['dashboard']['normal']['core'];

		$our_widget = array(
			self::WIDGET_ID => $normal_core_widgets[ self::WIDGET_ID ],
		);

		unset( $normal_core_widgets[ self::WIDGET_ID ] );

		$displaced_widget_id   = null;
		$displaced_widget_data = null;

		if ( ! empty( $normal_core_widgets ) ) {
			$normal_widget_keys = array_keys( $normal_core_widgets );
			$displaced_widget_id = reset( $normal_widget_keys );

			if ( false !== $displaced_widget_id && isset( $normal_core_widgets[ $displaced_widget_id ] ) ) {
				$displaced_widget_data = $normal_core_widgets[ $displaced_widget_id ];

				unset( $normal_core_widgets[ $displaced_widget_id ] );
			}
		}

		$wp_meta_boxes['dashboard']['normal']['core'] = $our_widget + $normal_core_widgets;

		if ( null !== $displaced_widget_id && null !== $displaced_widget_data ) {
			$side_core_widgets = $wp_meta_boxes['dashboard']['side']['core'];

			if ( isset( $side_core_widgets[ $displaced_widget_id ] ) ) {
				unset( $side_core_widgets[ $displaced_widget_id ] );
			}

			$wp_meta_boxes['dashboard']['side']['core'] = array(
				$displaced_widget_id => $displaced_widget_data,
			) + $side_core_widgets;
		}
	}

	public static function filter_dashboard_order( $order ): array {
		$order = is_array( $order ) ? $order : array();

		$normal = isset( $order['normal'] ) ? (string) $order['normal'] : '';
		$side   = isset( $order['side'] ) ? (string) $order['side'] : '';

		$normal_ids = self::csv_to_array( $normal );
		$side_ids   = self::csv_to_array( $side );

		$normal_ids = array_values( array_diff( $normal_ids, array( self::WIDGET_ID ) ) );
		$side_ids   = array_values( array_diff( $side_ids, array( self::WIDGET_ID ) ) );


		if ( ! empty( $normal_ids ) || isset( $order['normal'] ) || empty( $side_ids ) ) {
			array_unshift( $normal_ids, self::WIDGET_ID );
		} else {
			array_unshift( $side_ids, self::WIDGET_ID );
		}

		$order['normal'] = implode( ',', array_unique( $normal_ids ) );
		$order['side']   = implode( ',', array_unique( $side_ids ) );

		return $order;
	}

	private static function csv_to_array( string $value ): array {
		if ( '' === trim( $value ) ) {
			return array();
		}

		$items = array_map( 'trim', explode( ',', $value ) );
		$items = array_filter(
			$items,
			static function ( $item ) {
				return '' !== $item;
			}
		);

		return array_values( $items );
	}
	public static function render_widget(): void {
		$logo_url         = trailingslashit( AEGISIFY_CORE_URL ) . 'assets/aegisify_logo1_small.png';
		$buy_now_url      = 'https://www.paypal.com/ncp/payment/XPUYRBYTKER3U';
		$blog_url         = 'https://aegisify.com/blog/';
		$support_url      = 'https://aegisify.com/help-center/';
		$ticket_url       = 'https://aegisify.com/profile/';
		$challenge_url    = 'https://aegisify.com/aegisify-core-user-guide/';
		$rss_feed_url     = 'https://aegisify.com/feed/';
		$custom_text      = get_option(
			'aegisify_dashboard_news_custom_text',
			'Enterprise-grade WordPress security, backup, SEO, spam protection, WAF, sitemap intelligence, Short Links, AI and more "All-In-One Platform".'
		);

		echo '<div class="aegisify-dashboard-news-widget" style="margin:0; padding:0;">';

		// Header.
		echo '<div style="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:12px;">';

		echo '<div style="flex:1 1 auto;">';

		echo '<a href="' . esc_url( $buy_now_url ) . '" target="_blank" rel="noopener noreferrer" style="display:inline-block; background:#ED4A00; color:#ffffff; text-decoration:none; font-weight:600; padding:10px 16px; border-radius:4px;">';
		echo esc_html__( 'Only $49.99/mo - Buy Now', 'aegisify' );
		echo '</a>';
		echo '</div>';

		echo '<div style="flex:0 0 auto; text-align:right;">';
		echo '<img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr__( 'Aegisify Logo', 'aegisify' ) . '" style="max-width:240px; height:auto;" />';
		echo '</div>';

		echo '</div>';

		// Custom text.
		echo '<div style="margin:0 0 14px 0; font-size:13px; line-height:1.6;">';
		echo wp_kses_post( wpautop( $custom_text ) );
		echo '</div>';

		// Feed.
		$items = self::get_feed_items( $rss_feed_url, 2 );

		echo '<div style="margin-top:4px;">';

		if ( ! empty( $items ) ) {
			echo '<ul style="margin:0; padding:0; list-style:none;">';

			foreach ( $items as $item ) {
				$title = isset( $item['title'] ) ? $item['title'] : '';
				$link  = isset( $item['link'] ) ? $item['link'] : '';
				$desc  = isset( $item['desc'] ) ? $item['desc'] : '';

				echo '<li style="margin:0 0 14px 0; padding:0 0 14px 0; border-bottom:1px solid #e0e0e0;">';

				echo '<div style="font-size:15px; font-weight:600; margin:0 0 6px 0;">';
				echo '<a href="' . esc_url( $link ) . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">' . esc_html( $title ) . '</a>';
				echo '</div>';

				if ( ! empty( $desc ) ) {
					echo '<div style="font-size:13px; line-height:1.6; color:#444;">' . esc_html( $desc ) . '</div>';
				}

				echo '</li>';
			}

			echo '</ul>';
		} else {
			echo '<p style="margin:0 0 14px 0;">' . esc_html__( 'No recent posts available right now.', 'aegisify' ) . '</p>';
		}

		echo '</div>';

		// Footer links.
		echo '<div style="display:flex; flex-wrap:wrap; gap:14px; margin-top:8px; padding-top:10px; border-top:1px solid #e0e0e0;">';

		echo '<a href="' . esc_url( $blog_url ) . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">📰 ' . esc_html__( 'Blog', 'aegisify' ) . '</a>';
		echo '<a href="' . esc_url( $support_url ) . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">🛟 ' . esc_html__( 'Support', 'aegisify' ) . '</a>';
		echo '<a href="' . esc_url( $ticket_url ) . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">🎫 ' . esc_html__( 'Ticket', 'aegisify' ) . '</a>';
		echo '<a href="' . esc_url( $challenge_url ) . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">🚀 ' . esc_html__( 'Take the 30 Day Challenge', 'aegisify' ) . '</a>';

		echo '</div>';

		echo '</div>';
	}

	private static function get_feed_items( string $feed_url, int $limit = 2 ): array {
		if ( ! function_exists( 'fetch_feed' ) ) {
			require_once ABSPATH . WPINC . '/feed.php';
		}

		$feed = fetch_feed( $feed_url );

		if ( is_wp_error( $feed ) ) {
			return array();
		}

		$maxitems = $feed->get_item_quantity( $limit );
		$rss_items = $feed->get_items( 0, $maxitems );

		if ( empty( $rss_items ) ) {
			return array();
		}

		$items = array();

		foreach ( $rss_items as $rss_item ) {
			$description = wp_strip_all_tags( (string) $rss_item->get_description() );
			$description = html_entity_decode( $description, ENT_QUOTES, get_bloginfo( 'charset' ) );
			$description = wp_trim_words( $description, 28, '...' );

			$items[] = array(
				'title' => (string) $rss_item->get_title(),
				'link'  => (string) $rss_item->get_link(),
				'desc'  => $description,
			);
		}

		return $items;
	}
}