<?php

/**
 * The dashboard-specific functionality of the plugin.
 *
 * @link       https://kaizencoders.com
 * @since      1.0.0
 *
 * @package    MagicLink
 * @subpackage MagicLink/admin
 */

namespace KaizenCoders\MagicLink;

use KaizenCoders\MagicLink\Admin\Magic_Links_Table;

/**
 * The dashboard-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the dashboard-specific stylesheet and JavaScript.
 *
 * @package    MagicLink
 * @subpackage MagicLink/admin
 * @author     KaizenCoders <hello@kaizencoders.com>
 */
class Admin {
	/**
	 * The plugin's instance.
	 *
	 * @since  1.0.0
	 * @access private
	 * @var    Plugin $plugin This plugin's instance.
	 */
	private $plugin;

	/**
	 * Magic Links list table instance.
	 *
	 * @since  1.2.1
	 * @var    Admin\Magic_Links_Table
	 */
	public $magic_links_table;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param  Plugin  $plugin  This plugin's instance.
	 *
	 * @since 1.0.0
	 *
	 */
	public function __construct( Plugin $plugin ) {
		$this->plugin = $plugin;
	}

	/**
	 * Register the JavaScript for the dashboard.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {
		$version = KC_ML_PLUGIN_VERSION;
		if ( defined( 'KC_ML_DEV_MODE' ) && KC_ML_DEV_MODE ) {
			$version = time();
		}

		wp_enqueue_script( 'magic-link-script', \plugin_dir_url( __DIR__ ) . 'dist/scripts/magic-link.js', [
			'jquery',
			'wp-i18n',
		],
			$version, true );
		wp_localize_script( 'magic-link-script', 'magicLinkAjax', [
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'generate_magic_link_nonce' ),
		] );

	}

	/**
	 * Register the stylesheets for the Dashboard.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {
		if ( Helper::is_plugin_admin_screen() ) {
			\wp_enqueue_style(
				'magic-link-main',
				\plugin_dir_url( __DIR__ ) . 'dist/styles/app.css',
				array(),
				$this->plugin->get_version(),
				'all'
			);

			\wp_enqueue_style(
				'magic-link-admin',
				\plugin_dir_url( __DIR__ ) . 'dist/styles/magic-link-admin.css',
				array(),
				$this->plugin->get_version(),
				'all'
			);
		}
	}

	public function add_magic_link_column( $columns ) {
		$columns['magic_link'] = __( 'Magic Link', 'magic-link' );

		return $columns;

	}

	public function show_magic_link_button( $value, $column_name, $user_id ) {
		$magic_link = '';
		if ( $column_name == 'magic_link' ) {
			$magic_link .= '<button class="generate-magic-link button" data-user-id="' . esc_attr( $user_id ) . '">' . __( 'Generate Magic Link',
					'magic-link' ) . '</button><br><span class="magic-link" id="magic-link-' . esc_attr( $user_id ) . '"></span>';
		}

		$link = Helper::get_login_link( $user_id );

		if ( ! empty( $link ) ) {
			$magic_link .= '<input type="text" value="' . $link . '" readonly><button class="copy-magic-link button">' . __( 'Copy',
					'magic-link' ) . '</button>';
		}

		return $magic_link;
	}

	public function generate_magic_link() {
		check_ajax_referer( 'generate_magic_link_nonce', 'nonce' );

		if ( empty( $_POST['user_id'] ) ) {
			wp_send_json_error( 'User ID is missing.' );
		}

		$user_id = intval( wp_unslash( $_POST['user_id'] ) );

		if ( ! $user_id ) {
			wp_send_json_error( 'Invalid user ID.' );
		}

		$pre_check = apply_filters( 'kc_ml_pre_generate_magic_link', null );
		if ( is_wp_error( $pre_check ) ) {
			wp_send_json_error( $pre_check->get_error_message() );
		}

		$user = get_user_by( 'id', $user_id );

		if ( ! $user ) {
			wp_send_json_error( __( 'User not found.', 'magic-link' ) );
		}

		$email_validation = apply_filters( 'kc_ml_validate_email_for_magic_link', null, $user->user_email );
		if ( is_wp_error( $email_validation ) ) {
			wp_send_json_error( $email_validation->get_error_message() );
		}

		$magic_link = Helper::create_login_link( $user );

		wp_send_json_success( [ 'magic_link' => $magic_link ] );
	}

	public function add_admin_menu() {
		add_menu_page(
			__( 'Magic Link', 'magic-link' ),
			__( 'Magic Link', 'magic-link' ),
			'manage_options',
			'magic-link',
			array(
				$this,
				'render_dashboard',
			),
			'data:image/svg+xml;base64,PD94bWwgdmVy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0xNy42MzRsLTYxLjA1MS04MS44NDRsMzIuNzgxLTk2LjY5NiBDNDgyLjQ0Nyw0Ni43NjYsNDgwLjkwMyw0MC4wODYsNDc2LjQwMywzNS41OTh6Ii8+IDwvc3ZnPg==',
			30
		);

		new \KaizenCoders\MagicLink\Admin\Settings();

		$magic_links_hook = add_submenu_page(
			'magic-link',
			__( 'Magic Links', 'magic-link' ),
			__( 'Magic Links', 'magic-link' ),
			'manage_options',
			'magic-link-links',
			[
				$this,
				'render_magic_links_page',
			],
			5
		);

		add_action( "load-{$magic_links_hook}", [ $this, 'add_magic_links_screen_options' ] );

		$hook = add_submenu_page(
			'magic-link',
			__( 'Other Products', 'magic-link' ),
			__( 'Other Products', 'magic-link' ),
			'manage_options',
			'magic-link-other-products',
			[
				$this,
				'render_other_products_page',
			],
			9
		);

		do_action( 'kc_ml_admin_menu' );
	}

	public function render_dashboard() {
		include_once KC_ML_ADMIN_TEMPLATES_DIR . '/landing.php';
	}

	public function render_other_products_page() {
		include_once KC_ML_ADMIN_TEMPLATES_DIR . '/other-products.php';
	}

	/**
	 * Render Magic Links list table page.
	 *
	 * @since 1.2.1
	 */
	public function render_magic_links_page() {
		$magic_links_table = new \KaizenCoders\MagicLink\Admin\Magic_Links_Table();
		$magic_links_table->render();
	}

	/**
	 * Add screen options for Magic Links page.
	 *
	 * @since 1.2.1
	 */
	public function add_magic_links_screen_options() {
		$action = Helper::get_request_data( 'action' );

		if ( 'new' === $action ) {
			return;
		}

		\KaizenCoders\MagicLink\Admin\Magic_Links_Table::screen_options();
	}

	/**
	 * Save screen options.
	 *
	 * @param mixed  $status Current status.
	 * @param string $option Option name.
	 * @param mixed  $value  Option value.
	 *
	 * @return mixed
	 *
	 * @since 1.2.1
	 */
	public function save_screen_options( $status, $option, $value ) {
		if ( \KaizenCoders\MagicLink\Admin\Magic_Links_Table::$option_per_page === $option ) {
			return absint( $value );
		}

		return $status;
	}
	/**
	 * Remove all admin notices
	 *
	 * @since 1.0.0
	 */
	public function remove_admin_notices() {
		global $wp_filter;

		if ( ! Helper::is_plugin_admin_screen() ) {
			return;
		}

		$get_page = Helper::get_request_data( 'page' );

		if ( ! empty( $get_page ) && 'url_shortify' == $get_page ) {
			remove_all_actions( 'admin_notices' );
		} else {
			$allow_display_notices = [
				'show_review_notice',
				'kc_ml_fail_php_version_notice',
				'kc_ml_show_admin_notice',
				'show_custom_notices',
				'handle_promotions',
				'_admin_notices_hook',
			];

			$filters = [
				'admin_notices',
				'user_admin_notices',
				'all_admin_notices',
			];

			foreach ( $filters as $filter ) {
				if ( ! empty( $wp_filter[ $filter ]->callbacks ) && is_array( $wp_filter[ $filter ]->callbacks ) ) {
					foreach ( $wp_filter[ $filter ]->callbacks as $priority => $callbacks ) {
						foreach ( $callbacks as $name => $details ) {
							if ( is_object( $details['function'] ) && $details['function'] instanceof \Closure ) {
								unset( $wp_filter[ $filter ]->callbacks[ $priority ][ $name ] );
								continue;
							}

							if ( ! empty( $details['function'][0] ) && is_object( $details['function'][0] ) && count( $details['function'] ) == 2 ) {
								$notice_callback_name = $details['function'][1];
								if ( ! in_array( $notice_callback_name, $allow_display_notices ) ) {
									unset( $wp_filter[ $filter ]->callbacks[ $priority ][ $name ] );
								}
							}

							if ( ! empty( $details['function'] ) && is_string( $details['function'] ) ) {
								if ( ! in_array( $details['function'], $allow_display_notices ) ) {
									unset( $wp_filter[ $filter ]->callbacks[ $priority ][ $name ] );
								}
							}
						}
					}
				}

			}
		}

	}

	/**
	 * Update plugin notice
	 *
	 * @param $response
	 *
	 * @param $data
	 *
	 * @since 1.1.9
	 *
	 */
	public function in_plugin_update_message( $data, $response ) {
		if ( isset( $data['upgrade_notice'] ) ) {
			echo $data['upgrade_notice'];
		}
	}

	/**
	 * Add Plugin Promotion Footer.
	 *
	 * @return void
	 *
	 * @since 1.1.9
	 */
	public function promote_magic_link() {
		if ( Helper::is_plugin_admin_screen() ) {
			$links = [
				[
					'url'    => KC_ML()->is_pro() ? 'https://kaizencoders.com/contact/' : 'https://wordpress.org/support/plugin/magic-link/',
					'text'   => __( 'Support', 'magic-link' ),
					'target' => '_blank',
				],
				[
					'url'    => 'https://docs.kaizencoders.com/',
					'text'   => __( 'Docs', 'pretty-link' ),
					'target' => '_blank',
				],
			];

			$title = __( 'Made with ♥ by the team KaizenCoders', 'magic-link' );

			require_once( KC_ML_ADMIN_TEMPLATES_DIR . '/footer-promotion.php' );
		}
	}

	/**
	 * Update admin footer text
	 *
	 * @param $footer_text
	 *
	 * @return string
	 *
	 * @since 1.1.9
	 *
	 */
	public function update_admin_footer_text( $footer_text ) {
		// Update Footer admin only on URL Shortify pages
		if ( Helper::is_plugin_admin_screen() ) {
			$wordpress_url = 'https://www.wordpress.org';
			$website_url   = 'https://www.kaizencoders.com';

			$plugin_name = ( KC_ML()->is_pro() ) ? 'Magic Link PRO' : 'Magic Link';

			/* translators: 1: WordPress link, 2: Plugin name, 3: Plugin version, 4: KaizenCoders link */
			$footer_text = sprintf( __( '<span id="footer-thankyou">Thank you for creating with <a href="%1$s" target="_blank">WordPress</a> | %2$s <b>%3$s</b>. Made with ❤️ by the team <a href="%4$s" target="_blank">KaizenCoders</a></span>',
				'url-shortify' ), $wordpress_url, $plugin_name, KC_ML_PLUGIN_VERSION, $website_url );
		}

		return $footer_text;
	}

}
