<?php
/**
 * Approval admin class file.
 *
 * @package WholesaleNode_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Adds approval status column and actions to the WordPress Users list.
 */
class WOOWSNFree_Approval_Admin {

	/**
	 * Attach all hooks.
	 */
	public static function init() {
		if ( ! is_admin() ) {
			return;
		}

		add_filter( 'manage_users_columns',          array( __CLASS__, 'add_column' ) );
		add_filter( 'manage_users_custom_column',    array( __CLASS__, 'column_content' ), 10, 3 );
		add_filter( 'user_row_actions',              array( __CLASS__, 'row_actions' ), 10, 2 );
		add_action( 'admin_action_woowsnfree_approve_user', array( __CLASS__, 'handle_approve' ) );
		add_action( 'admin_action_woowsnfree_reject_user',  array( __CLASS__, 'handle_reject' ) );
		add_action( 'restrict_manage_users',         array( __CLASS__, 'filter_dropdown' ) );
		add_filter( 'pre_get_users',                 array( __CLASS__, 'apply_filter' ) );
		add_action( 'admin_notices',                 array( __CLASS__, 'action_notices' ) );
		add_action( 'admin_enqueue_scripts', 		 array( __CLASS__, 'inline_styles' ) );
	}

	/**
	 * Add Approval column after Role.
	 *
	 * @param array $columns Existing columns.
	 * @return array
	 */
	public static function add_column( $columns ) {
		$new = array();
		foreach ( $columns as $key => $label ) {
			$new[ $key ] = $label;
			if ( $key === 'role' ) {
				$new['woowsn_approval'] = __( 'B2B Approval', 'wholesalenode-for-woocommerce' );
			}
		}
		if ( ! isset( $new['woowsn_approval'] ) ) {
			$new['woowsn_approval'] = __( 'B2B Approval', 'wholesalenode-for-woocommerce' );
		}
		return $new;
	}

	/**
	 * Render the Approval column cell.
	 *
	 * @param string $output      Default column output.
	 * @param string $column_name Column name.
	 * @param int    $user_id     User ID.
	 * @return string
	 */
	public static function column_content( $output, $column_name, $user_id ) {
		if ( $column_name !== 'woowsn_approval' ) {
			return $output;
		}

		$status    = get_user_meta( $user_id, 'woowsn_approval_status', true );
		$user_type = get_user_meta( $user_id, 'woowsn_user_type', true );

		if ( ! $status && ! $user_type ) {
			return '&mdash;';
		}
		if ( ! $status && $user_type ) {
			$status = 'pending';
		}

		$map = array(
			'pending'  => array( __( 'Pending', 'wholesalenode-for-woocommerce' ),  'woowsn-free-badge-pending' ),
			'approved' => array( __( 'Approved', 'wholesalenode-for-woocommerce' ), 'woowsn-free-badge-approved' ),
			'rejected' => array( __( 'Rejected', 'wholesalenode-for-woocommerce' ), 'woowsn-free-badge-rejected' ),
		);

		list( $label, $class ) = $map[ $status ] ?? array( ucfirst( $status ), '' );

		return sprintf( '<span class="woowsn-free-status-badge %s">%s</span>', esc_attr( $class ), esc_html( $label ) );
	}

	/**
	 * Add quick Approve / Reject action links to each user row.
	 *
	 * @param array   $actions Existing row actions.
	 * @param WP_User $user    User object.
	 * @return array
	 */
	public static function row_actions( $actions, $user ) {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return $actions;
		}

		$status    = get_user_meta( $user->ID, 'woowsn_approval_status', true );
		$user_type = get_user_meta( $user->ID, 'woowsn_user_type', true );

		if ( ! $status && ! $user_type ) {
			return $actions;
		}
		if ( ! $status ) {
			$status = 'pending';
		}

		$nonce = wp_create_nonce( 'woowsnfree_approval_' . $user->ID );

		if ( $status === 'pending' || $status === 'rejected' ) {
			$actions['woowsnfree_approve'] = sprintf(
				'<a href="%s" style="color:#16a34a;font-weight:600;">%s</a>',
				esc_url( admin_url( 'users.php?action=woowsnfree_approve_user&user=' . $user->ID . '&_wpnonce=' . $nonce ) ),
				esc_html__( 'Approve', 'wholesalenode-for-woocommerce' )
			);
		}
		if ( $status === 'pending' || $status === 'approved' ) {
			$actions['woowsnfree_reject'] = sprintf(
				'<a href="%s" style="color:#dc2626;">%s</a>',
				esc_url( admin_url( 'users.php?action=woowsnfree_reject_user&user=' . $user->ID . '&_wpnonce=' . $nonce ) ),
				esc_html__( 'Reject', 'wholesalenode-for-woocommerce' )
			);
		}

		return $actions;
	}

	/**
	 * Process approve action.
	 */
	public static function handle_approve() {
		self::handle_decision( 'approved' );
	}

	/**
	 * Process reject action.
	 */
	public static function handle_reject() {
		self::handle_decision( 'rejected' );
	}

	/**
	 * Shared decision handler.
	 *
	 * @param string $new_status approved | rejected
	 */
	private static function handle_decision( $new_status ) {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'wholesalenode-for-woocommerce' ) );
		}

		$user_id = isset( $_GET['user'] ) ? intval( $_GET['user'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! $user_id ) {
			wp_die( esc_html__( 'Invalid user.', 'wholesalenode-for-woocommerce' ) );
		}

		check_admin_referer( 'woowsnfree_approval_' . $user_id );

		update_user_meta( $user_id, 'woowsn_approval_status', $new_status );

		if ( $new_status === 'approved' ) {
			delete_user_meta( $user_id, 'woowsn_account_disabled' );
			self::send_decision_email( $user_id, 'approved' );
		} elseif ( $new_status === 'rejected' ) {
			update_user_meta( $user_id, 'woowsn_account_disabled', '1' );
			self::send_decision_email( $user_id, 'rejected' );
		}

		wp_safe_redirect( add_query_arg(
			array( 'woowsnfree_action' => $new_status, 'woowsnfree_user' => $user_id ),
			admin_url( 'users.php' )
		) );
		exit;
	}

	/**
	 * Send approval/rejection notification email to the user.
	 *
	 * @param int    $user_id    User ID.
	 * @param string $new_status approved | rejected
	 */
	private static function send_decision_email( $user_id, $new_status ) {
		$user = get_userdata( $user_id );
		if ( ! $user ) {
			return;
		}

		$site  = get_bloginfo( 'name' );
		$login = wc_get_page_permalink( 'myaccount' ) ?: wp_login_url();

		if ( $new_status === 'approved' ) {
			$subject = sprintf(
				/* translators: %s: site name */
				__( 'Your account at %s has been approved', 'wholesalenode-for-woocommerce' ),
				$site
			);
			$message = sprintf(
				/* translators: 1: display name, 2: site name, 3: login URL */
				__( "Hi %1\$s,\n\nYour B2B account at %2\$s has been approved.\n\nYou can now log in at:\n%3\$s\n\nThank you!", 'wholesalenode-for-woocommerce' ),
				$user->display_name,
				$site,
				$login
			);
		} else {
			$subject = sprintf(
				/* translators: %s: site name */
				__( 'Your account application at %s', 'wholesalenode-for-woocommerce' ),
				$site
			);
			$message = sprintf(
				/* translators: 1: display name, 2: site name */
				__( "Hi %1\$s,\n\nThank you for applying for a B2B account at %2\$s.\n\nUnfortunately, we were unable to approve your application at this time. Please contact us if you have any questions.", 'wholesalenode-for-woocommerce' ),
				$user->display_name,
				$site
			);
		}

		wp_mail( $user->user_email, $subject, $message );
	}

	/**
	 * Approval status filter dropdown above the users table.
	 */
	public static function filter_dropdown() {
		$current = isset( $_GET['woowsn_approval_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['woowsn_approval_filter'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		?>
		<label for="woowsn_approval_filter" style="margin-left:8px;"><?php esc_html_e( 'B2B Approval:', 'wholesalenode-for-woocommerce' ); ?></label>
		<select name="woowsn_approval_filter" id="woowsn_approval_filter" style="margin-left:4px;">
			<option value=""><?php esc_html_e( 'All', 'wholesalenode-for-woocommerce' ); ?></option>
			<option value="pending"  <?php selected( $current, 'pending' ); ?>><?php esc_html_e( 'Pending', 'wholesalenode-for-woocommerce' ); ?></option>
			<option value="approved" <?php selected( $current, 'approved' ); ?>><?php esc_html_e( 'Approved', 'wholesalenode-for-woocommerce' ); ?></option>
			<option value="rejected" <?php selected( $current, 'rejected' ); ?>><?php esc_html_e( 'Rejected', 'wholesalenode-for-woocommerce' ); ?></option>
		</select>
		<?php
	}

	/**
	 * Apply approval filter to WP_User_Query.
	 *
	 * @param WP_User_Query $query User query.
	 */
	public static function apply_filter( $query ) {
		if ( ! is_admin() ) {
			return;
		}
		$filter = isset( $_GET['woowsn_approval_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['woowsn_approval_filter'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! $filter ) {
			return;
		}

		$meta_query = (array) $query->get( 'meta_query' );

		if ( $filter === 'pending' ) {
			$meta_query[] = array(
				'relation' => 'OR',
				array( 'key' => 'woowsn_approval_status', 'value' => 'pending', 'compare' => '=' ),
				array(
					'relation' => 'AND',
					array( 'key' => 'woowsn_user_type', 'compare' => 'EXISTS' ),
					array( 'key' => 'woowsn_approval_status', 'compare' => 'NOT EXISTS' ),
				),
			);
		} else {
			$meta_query[] = array( 'key' => 'woowsn_approval_status', 'value' => $filter, 'compare' => '=' );
		}

		$query->set( 'meta_query', $meta_query );
	}

	/**
	 * Admin notice after approve/reject redirect.
	 */
	public static function action_notices() {
		$action  = isset( $_GET['woowsnfree_action'] ) ? sanitize_text_field( wp_unslash( $_GET['woowsnfree_action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$user_id = isset( $_GET['woowsnfree_user'] )  ? intval( $_GET['woowsnfree_user'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		if ( ! $action || ! $user_id ) {
			return;
		}

		$user = get_userdata( $user_id );
		$name = $user ? esc_html( $user->display_name ) : '#' . $user_id;
		$html = array( 'strong' => array() );

		if ( $action === 'approved' ) {
			/* translators: %s: user display name */
			$msg  = wp_kses( sprintf( __( '%s has been approved. An approval email was sent.', 'wholesalenode-for-woocommerce' ), '<strong>' . $name . '</strong>' ), $html );
			$type = 'success';
		} else {
			/* translators: %s: user display name */
			$msg  = wp_kses( sprintf( __( '%s has been rejected.', 'wholesalenode-for-woocommerce' ), '<strong>' . $name . '</strong>' ), $html );
			$type = 'warning';
		}

		echo '<div class="notice notice-' . esc_attr( $type ) . ' is-dismissible"><p>' . $msg . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	/**
	 * Inline CSS for badge styling.
	 */
	public static function inline_styles() {
		$css = '
			.woowsn-free-status-badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.3px}
			.woowsn-free-badge-pending{background:#fef3c7;color:#92400e}
			.woowsn-free-badge-approved{background:#dcfce7;color:#166534}
			.woowsn-free-badge-rejected{background:#fee2e2;color:#991b1b}
		';
		wp_add_inline_style( 'woowsn-free-backend', $css );
	}
}
