<?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( $hook ) {
		$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' ),
		] );

		// Enqueue ApexCharts only on the Magic Link dashboard page.
		if ( $hook === 'toplevel_page_magic-link' ) {
			wp_enqueue_script(
				'kc-ml-apexcharts',
				\plugin_dir_url( __DIR__ ) . 'dist/vendor/apexcharts.min.js',
				[],
				'3.46.0',
				true
			);
		}
	}

	/**
	 * 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;
	}

	/**
	 * Add "Revoke Magic Links" as a row action on the users.php list table.
	 *
	 * @param  array    $actions Existing actions.
	 * @param  \WP_User $user    User the row represents.
	 *
	 * @return array
	 *
	 * @since 1.4.0
	 */
	public function add_user_row_action( $actions, $user ) {
		if ( ! current_user_can( 'edit_users' ) ) {
			return $actions;
		}
		$url = wp_nonce_url(
			add_query_arg(
				array(
					'action'  => 'kc_ml_revoke_links',
					'user_id' => $user->ID,
				),
				admin_url( 'users.php' )
			),
			'kc_ml_revoke_links_' . $user->ID
		);
		$actions['kc_ml_revoke'] = '<a href="' . esc_url( $url ) . '">' . esc_html__( 'Revoke Magic Links', 'magic-link' ) . '</a>';

		return $actions;
	}

	/**
	 * Handle the row-action click.
	 *
	 * @return void
	 *
	 * @since 1.4.0
	 */
	public function handle_revoke_user_links() {
		if ( ! isset( $_GET['action'] ) || 'kc_ml_revoke_links' !== $_GET['action'] ) {
			return;
		}
		if ( ! current_user_can( 'edit_users' ) ) {
			wp_die( esc_html__( 'You do not have permission to revoke magic links.', 'magic-link' ) );
		}
		$user_id = isset( $_GET['user_id'] ) ? (int) $_GET['user_id'] : 0;
		check_admin_referer( 'kc_ml_revoke_links_' . $user_id );

		$count = Helper::revoke_user_tokens( $user_id );

		wp_safe_redirect(
			add_query_arg(
				array(
					'kc_ml_revoked' => $count,
				),
				admin_url( 'users.php' )
			)
		);
		exit;
	}

	/**
	 * Register a bulk action on users.php.
	 *
	 * @param  array $actions Bulk actions.
	 *
	 * @return array
	 *
	 * @since 1.4.0
	 */
	public function add_bulk_revoke_action( $actions ) {
		$actions['kc_ml_revoke_links'] = __( 'Revoke Magic Links', 'magic-link' );

		return $actions;
	}

	/**
	 * Handle the bulk action submission.
	 *
	 * @param  string $sendback Redirect URL.
	 * @param  string $action   Selected action slug.
	 * @param  array  $user_ids IDs to act on.
	 *
	 * @return string
	 *
	 * @since 1.4.0
	 */
	public function handle_bulk_revoke_action( $sendback, $action, $user_ids ) {
		if ( 'kc_ml_revoke_links' !== $action ) {
			return $sendback;
		}
		if ( ! current_user_can( 'edit_users' ) ) {
			return $sendback;
		}
		$total = 0;
		foreach ( (array) $user_ids as $id ) {
			$total += Helper::revoke_user_tokens( (int) $id );
		}
		return add_query_arg( 'kc_ml_revoked', $total, $sendback );
	}

	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,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/PiA8c3ZnIGhlaWdodD0iODAwcHgiIHdpZHRoPSI4MDBweCIgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmlld0JveD0iMCAwIDUxMi4wMDIgNTEyLjAwMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+IDxwYXRoIHN0eWxlPSJmaWxsOiM4MDY3NDk7IiBkPSJNMzAwLjg3NSwyMTEuMTI2bC01NC4wMzMtMTYuNzg4TDQuODkyLDQzNi4yODljLTYuNTIxLDYuNTIxLTYuNTIxLDE3LjA4NiwwLDIzLjYwN2w0Ny4yMTQsNDcuMjE0IGMzLjI2MSwzLjI2MSw3LjUzMyw0Ljg5MSwxMS44MDMsNC44OTFjNC4yNzIsMCw4LjU0My0xLjYzLDExLjgwMy00Ljg5MWwyNDEuOTUtMjQxLjk1TDMwMC44NzUsMjExLjEyNnoiLz4gPHBhdGggc3R5bGU9ImZpbGw6IzVGNEQzNzsiIGQ9Ik0zMDAuODc1LDIxMS4xMjZMMzAwLjg3NSwyMTEuMTI2TDI4LjQ5OSw0ODMuNTAzbDIzLjYwNywyMy42MDcgYzMuMjYxLDMuMjYxLDcuNTMzLD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RjMS44OTEsNi4wNjUsNy4wNTQsMTAuNTQzLDEzLjMzNiwxMS41MzEgYzAuODY5LDAuMTQxLDEuNzQsMC4yMDcsMi42MDksMC4yMDdjNS4zNjksMCwxMC40NjYtMi41ODcsMTMuNjI5LTcuMDU0bDU4Ljk1My04My4yMTNsMTAyLjA2OSwxLjQ0MmMwLjA3NiwwLDAuMTUyLDAsMC4yMTcsMCBjNi4yNzIsMCwxMi4wMjEtMy42NjEsMTQuODc5LTkuMjU4YzIuODgtNS42NjMsMi4zMDQtMTIuNTM2LTEuNS0xNy42MzRsLTYxLjA1MS04MS44NDRsMzIuNzgxLTk2LjY5NiBDNDgyLjQ0Nyw0Ni43NjYsNDgwLjkwMyw0MC4wODYsNDc2LjQwMywzNS41OTh6Ii8+IDwvc3ZnPg==',
			30
		);

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

		$magic_links_hook = add_submenu_page(
			'magic-link',
			__( 'Dashboard', 'magic-link' ),
			__( 'Dashboard', 'magic-link' ),
			'manage_options',
			'magic-link',
			[
				$this,
				'render_dashboard',
			],
			5
		);

		$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() {
		$is_pro = KC_ML()->is_pro();

		if ( ! empty( $_GET['refresh'] ) ) {
			check_admin_referer( 'kc_ml_dashboard_refresh' );
			( new \KaizenCoders\MagicLink\Admin\Controllers\DashboardController() )->bust_cache( $is_pro );
		}

		$days = isset( $_GET['days'] ) ? (int) $_GET['days'] : 7;
		$days = in_array( $days, [ 7, 30 ], true ) ? $days : 7;

		// Free users are capped at 7 days.
		if ( ! $is_pro ) {
			$days = 7;
		}

		$data = ( new \KaizenCoders\MagicLink\Admin\Controllers\DashboardController() )->get_data( $days, $is_pro );

		include KC_ML_ADMIN_TEMPLATES_DIR . '/dashboard.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',
				'maybe_render_magic_link_promo',
			];

			$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;
	}

}
