<?php
namespace BwlFaqManager\Api\Noticebox;

/**
 * Class BafAdminNotice
 *
 * Handles the display and management of admin notices for the BWL Advanced FAQ Manager plugin.
 *
 * @package BwlFaqManager
 */
class BafAdminNotice {

	/**
	 * List of admin notices to be displayed.
	 *
	 * @var array
	 */
	private array $notice_lists = [];

	/**
	 * BafAdminNotice constructor.
	 */
	public function __construct() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$this->set_plugin_installation_date();

		add_action( 'admin_notices', [ $this, 'display_plugin_notices' ] );
		// ajax call to save user settings.
		add_action( 'wp_ajax_baf_set_notice_status',  [ $this, 'save_notice_settings' ] );
	}

	/**
	 * Sets the plugin installation date if it is not already set.
	 */
	public function set_plugin_installation_date() {
		// Plugin Installation Date Time.
		if ( empty( get_option( BWL_BAF_INSTALLATION_DATE ) ) && current_user_can( 'manage_options' ) ) {
			update_option( BWL_BAF_INSTALLATION_DATE, date( 'Y-m-d H:i:s' ) );
		}
	}

	public function getTheLastPostCreatedInfo() {

		$days_ago = 0;

		// Get the date of the last post
		$last_post = wp_get_recent_posts([
			'post_type'   => BWL_BAF_CPT,
			'numberposts' => 1,
			'orderby'     => 'post_date',
			'order'       => 'DESC',
			'post_status' => 'publish',
		]);

		if ( ! empty( $last_post ) ) {
			$last_post_date = strtotime( $last_post[0]['post_date'] );
			$current_date   = time();
			$days_ago       = floor( ( $current_date - $last_post_date ) / ( 60 * 60 * 24 ) );

		}

		return $days_ago;
	}

	public function clearCookieVar( $cookieKey = '' ) {

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

		// Set the cookie variable to an empty string
		$cookie_name  = $cookieKey;
		$cookie_value = '';
		setcookie( $cookie_name, $cookie_value, time() - 3600, '/' ); // Expiry time in the past

	}


	public function setNewFaqNoticeReminder() {

		global $pagenow;

		$theLastPostCreatedInfo = $this->getTheLastPostCreatedInfo();

		$reminderDaysInterval = 14; // two weeks
		$isBafPage            = false;

		if ( $pagenow === 'edit.php' && isset( $_GET['post_type'] ) && $_GET['post_type'] === 'bwl_advanced_faq' ) {
			$isBafPage = true;
		}

		if ( $theLastPostCreatedInfo > $reminderDaysInterval && $isBafPage === true ) {

			$this->notice_lists[] = [
				'noticeClass' => 'warning',
				'msg'         => '<strong class="bwl_plugins_notice_text--success"><span class="dashicons dashicons-bell"></span>Quick Reminder:</strong> It\'s been <strong class="bwl_plugins_notice_text--danger">' . $theLastPostCreatedInfo . ' days</strong> since your last FAQ post, and your users really appreciated <span class="dashicons dashicons-heart bwl_plugins_notice_text--danger"></span> those. How about creating <a href="' . get_admin_url() . 'post-new.php?post_type=bwl_advanced_faq" class="bwl_plugins_notice_text--success bwl_plugins_notice_text--bold">a new one</a> for them?',
				'key'         => 'baf_last_created_post_status',
				'status'      => (int) get_option( 'baf_last_created_post_status' ),
			];
		}

		return null;
	}


	public function getAdminNoticeLists() {

		// Key MUST BE Unique. to be unique.
		// is-dismissible = display a close icon.
		// Classes: notice-success, notice-error, notice-warning. notice-info
		// display: 0, 1 [default: 1]

		$this->notice_lists = [

			[
				'noticeClass' => 'success ',
				'msg'         => '<span class="dashicons dashicons-megaphone bwl_plugins_notice_text--success"></span><strong class="bwl_plugins_notice_text--success bwl_plugins_notice_text--bold"> Good News !</strong> We have added a <a href="' . BWL_BAF_YOUTUBE_PLAYLIST . '" class="bwl_activation_link">YouTube Playlists</a> for the ' . BWL_BAF_PLUGIN_TITLE . ' plugin.',
				'key'         => 'baf_youtube_playlist_status',
				'status'      => (int) get_option( 'baf_youtube_playlist_status' ),
			],

			// analytics_page_status = aps
			[
				'noticeClass' => 'success',
				'msg'         => '<span class="dashicons dashicons-megaphone bwl_plugins_notice_text--success"></span> Good News ! We have improved the analytics feature of the FAQ posts. <a href="' . get_admin_url() . 'edit.php?post_type=bwl_advanced_faq&page=bwl-advanced-faq-analytics" class="bwl_activation_link">Check Now</a>.',
				'key'         => 'baf_aps_2_0_2',
				'status'      => (int) get_option( 'baf_aps_2_0_2' ),
			],

			[
				'noticeClass'    => 'error',
				'msg'            => '<span class="dashicons dashicons-lock bwl_plugins_notice_text--danger"></span> Please <a href="' . esc_url( get_admin_url() ) . 'admin.php?page=baf-license" class="bwl_plugins_notice_text--danger bwl_plugins_notice_text--bold">ACTIVATE YOUR COPY</a> of the plugin to unlock premium options and official support of ' . BWL_BAF_PLUGIN_TITLE . '.',
				'key'            => 'baf_license_activation_status',
				'status'         => ( BWL_BAF_VERIFIED === 1 ) ? 1 : 0,
				'is_dismissable' => 0,
			],

		];

		$this->setNewFaqNoticeReminder();

		return $this->notice_lists;
	}

	public function display_plugin_notices() {

		foreach ( $this->getAdminNoticeLists() as $notice ) {

			$status        = $notice['status'] ?? 0;
			$isDismissable = ( isset( $notice['is_dismissable'] ) && $notice['is_dismissable'] === 0 ) ? 0 : 1;

			if ( $isDismissable === 0 ) {
				$dismissableString = '';
				$dismissableClass  = '';
			} else {
				$dismissableString = '<button type="button" class="notice-dismiss baf_remove_notice" data-key="' . $notice['key'] . '">
        <span class="screen-reader-text">Dismiss this notice.</span>
        </button>';
				$dismissableClass  = ' is-dismissible';
			}

			if ( (int) $status !== 1 ) {
				echo '<div class="notice notice-' . trim( $notice['noticeClass'] ) . $dismissableClass . '">
                <p class="bwl_plugins_notice_text">' . trim( $notice['msg'] ) . '</p>
                ' . $dismissableString . '
              </div>';
			}
		}
	}

	/**
	 * Saves the notice settings via AJAX.
	 */
	public function save_notice_settings() {

		if ( empty( $_POST['noticeKey'] ) ) { // phpcs:ignore
			return;
		}

		$key = trim( $_POST['noticeKey'] ); // phpcs:ignore
		$data = [
			'key'    => $key,
			'status' => 0,
		];

		if ( current_user_can( 'manage_options' ) ) {
			// 1= notice closed by user, 0/empty=show the notice
			update_option( $key, 1 );
			$data['status'] = get_option( $key );
		}

		echo wp_json_encode( $data );

		die();
	}
}
