<?php

namespace KaizenCoders\MagicLink\CLI\Commands;

use KaizenCoders\MagicLink\Helper;

use \WP_CLI_Command as WP_CLI_Command;
use \WP_CLI as WP_CLI;

class MagicLink extends WP_CLI_Command {

	public function __construct() {
		// Ensure the main plugin class is loaded.
		if ( ! class_exists( 'KaizenCoders\MagicLink\Plugin' ) ) {
			WP_CLI::error( 'Magic Link plugin is not activated.' );
		}
	}

	/**
	 * Generate a magic link for any user.
	 *
	 * ## OPTIONS
	 *
	 * <user>
	 * : ID, email address, or user login for the user.
	 *
	 * [--count=<count>]
	 * : Generate a specified number of login tokens.
	 * ---
	 * default: 1
	 * ---
	 *
	 * [--redirect-to=<url>]
	 * : Target redirection URL upon login. It requires Magic Link Pro.
	 *
	 * [--send]
	 * : Send login email to the user
	 *
	 * ## EXAMPLES
	 *
	 *     # Generate Magic Link.
	 *     $ wp magic-link generate admin --send
	 *
	 * @param  array  $args        Positional CLI args.
	 * @param  array  $assoc_args  Associative CLI args.
	 */
	public function generate( $args, $assoc_args ) {
		$fetcher = new \WP_CLI\Fetchers\User();
		$user    = $fetcher->get_check( $args[0] );

		$count = isset( $assoc_args['count'] ) ? absint( $assoc_args['count'] ) : 1;

		if ( ! empty( $assoc_args['redirect-to'] ) && KC_ML()->is_pro() ) {
			$_POST['redirect_to'] = $assoc_args['redirect-to'];
		}

		for ( $i = 0; $i < $count; $i ++ ) {
			$data = [
				'email' => $user->user_email,
			];

			$magic_link = Helper::generate_magic_link( $data );

			if ( is_wp_error( $magic_link ) ) {
				WP_CLI::error( $magic_link->get_error_message() );
			} else {
				WP_CLI::success( 'Magic Link generated successfully', 'magic-link' );
				WP_CLI::log( $magic_link );
			}
		}

		$sent = false;
		if ( ! empty( $assoc_args['send'] ) ) {
			WP_CLI::log( esc_html__( 'Sending email to user', 'magic-link' ) );

			$sent = Helper::send_magic_link_email( $user, $magic_link );
			if ( $sent ) {
				WP_CLI::success( esc_html__( 'The email has been successfully sent.', 'magic-link' ) );
			} else {
				WP_CLI::error( esc_html__( 'The email could not be sent', 'magic-link' ) );
			}
		}

	}
}