<?php

namespace Gigneo\Modules;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use Gigneo\Notifications;

/**
 * Class Email_Verification
 *
 * Plugin term-meta class for Gigneo.
 *
 * @since 0.0.1
 */
class Email_Verification {


	/**
	 * The single instance of the class.
	 *
	 * @var Email_Verification|null
	 * @since 0.0.1
	 */
	private static $instance = null;

	/**
	 * Ensures only one instance of the class is loaded or can be loaded.
	 *
	 * @return Email_Verification
	 * @since 0.0.1
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Constructor for the class.
	 *
	 * @since 0.0.1
	 */
	public function __construct() {
		//Register notices
		add_action( 'wp', array( $this, 'register_notices' ) );

		//Handle Email Verification
		add_action( 'wp', array( $this, 'handle_email_verification' ) );

		//Send Verification Email
		add_action( 'wp_ajax_gigneo_email_verification', array( $this, 'send_verification_email' ) );

		//Verify/Unverify Email
		add_action( 'wp_ajax_gigneo_email_verify', array( $this, 'email_verify' ) );

		//Verification Action Button
		add_action( 'gigneo_post_type_actions', array( $this, 'post_type_actions' ), 10, 3 );
	}

	/**
	 * Registers email verification notices for the current user.
	 *
	 * @since 0.0.1
	 */
	public function register_notices() {

		$email_verified = get_user_meta( get_current_user_id(), '_gigneo_um_email_verified', true );

		if ( ! $email_verified ) {

			gigneo_register_notice(
				array(
					'id'             => 'email_verification',
					'title'          => esc_html__( 'Email unverified', 'gigneo' ),
					'description'    => esc_html__( 'Check your inbox and click the link to verify your email. Didn’t get it? Resend the email.', 'gigneo' ),
					'icon'           => 'hi hi-exclamation-circle',
					'type'           => 'warning', // info, success, warning, error
					'dismissible'    => false,
					'primary_button' => array(
						'label'  => esc_html__( 'Resend', 'gigneo' ),
						'id'     => 'gn-email-verification-btn',
						'url'    => gigneo_dashboard_url( 'setting', 'security' ),
						'target' => '_self',
						'icon'   => '',
						'class'  => 'gn-btn-warning',
					),
					'user_type'      => array( 'freelancer', 'employer' ),
					'excludes'       => array(
						'source' => array( 'message' ),
					),
				)
			);

		}
	}

	/**
	 * Handles the email verification process when the verification link is accessed.
	 *
	 * Validates the signed time-limited token, marks the user's email as verified,
	 * and redirects the user with a success message.
	 *
	 * @since 0.0.1
	 */
	public function handle_email_verification() {

        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only parameters no nonce required.
		$verify_email = isset( $_GET['gn_verify_email'] ) ? sanitize_text_field( wp_unslash( $_GET['gn_verify_email'] ) ) : '';
		$token        = ! empty( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : '';

		if ( empty( $verify_email ) || empty( $token ) ) {
			return;
		}
		$user_id = gigneo_verify_email_verification_token( $token );

		if ( ! $user_id ) {
			wp_die( esc_html__( 'Invalid or expired verification token.', 'gigneo' ) );
		}

		// Mark email as verified
		update_user_meta( $user_id, '_gigneo_um_email_verified', 1 );

		$profile_id = gigneo_profile_id( $user_id );

		if ( ! $profile_id ) {
			wp_die( esc_html__( 'Invalid or expired verification token.', 'gigneo' ) );
		}

		$notification_title = esc_html__( 'Email verified', 'gigneo' );

		$notification_content = esc_html__( 'Your email has been verified successfully.', 'gigneo' );

		Notifications::trigger_notification(
			$notification_title,
			$notification_content,
			'account',
			'email_verified',
			$profile_id
		);

		// Redirect to dashboard or profile page with a success message
		$redirect_url = remove_query_arg( array( 'gn_verify_email', 'token', 'user_id' ) );
		$redirect_url = add_query_arg( 'email_verified', '1', $redirect_url );

		wp_safe_redirect( $redirect_url );
		exit;
	}

	/**
	 * Sends a verification email to the current user.
	 *
	 * Validates the security nonce, checks user permissions, triggers the WooCommerce email,
	 * and returns a JSON response indicating success or failure.
	 *
	 * @since 0.0.1
	 */
	public function send_verification_email() {
		// Check if nonce is valid
		$security = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';
		if ( empty( $security ) || ! wp_verify_nonce( $security, 'gigneo_security' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Security verification failed. Please reload and try again.', 'gigneo' ) ), 403 );
		}

		$platform_access = gigneo_user_have_access();
		$profile_id      = gigneo_active_profile_id();
		$current_user    = wp_get_current_user();

		if ( empty( $current_user->ID ) || ! $platform_access || empty( $profile_id ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'You do not have permission to do that.', 'gigneo' ) ), 403 );
		}

		//Trigger Email
		$wc_mailer = WC()->mailer();
		$wc_emails = $wc_mailer->get_emails();

		$verification_link = gigneo_generate_email_verify_link( $current_user->ID );
		$wc_emails['Gigneo_Email_Verification']->trigger( $current_user->ID, $verification_link );

		$response            = array();
		$response['message'] = __( 'Verification link has been sent to your email.', 'gigneo' );

		wp_send_json_success( $response, 200 );
	}

	/**
	 * Verifies or unverifies a user's email via AJAX.
	 *
	 * Checks nonce and permissions, parses form data, updates user meta for email verification,
	 * and returns a JSON response indicating the result.
	 *
	 * @since 0.0.1
	 */
	public function email_verify() {

		// Check if nonce is valid
		$security = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';
		if ( empty( $security ) || ! wp_verify_nonce( $security, 'gigneo_security' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Security verification failed. Please reload and try again.', 'gigneo' ) ), 403 );
		}

		// Check if the user has permission to edit settings (usually admin)
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'You do not have permission to do that.', 'gigneo' ) ), 403 );
		}

		$id        = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0;
		$type      = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
		$author_id = get_post_field( 'post_author', $id );

		if ( empty( $id ) || empty( $type ) || ! $author_id ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Something went wrong1.', 'gigneo' ) ), 409 );
		}

		$email_verification = 'verify' === $type ? 1 : 0;

		update_user_meta( $author_id, '_gigneo_um_email_verified', $email_verification );

		$response            = array();
		$response['message'] = esc_html__( 'Email unverified successfully.', 'gigneo' );

		if ( 'verify' === $type ) {
			$response['message'] = esc_html__( 'Email verified successfully.', 'gigneo' );
		}

		wp_send_json_success( $response, 200 );
	}

	/**
	 * Displays the email verification action button for post types.
	 *
	 * Shows a button with an icon indicating whether the author's email is verified or not.
	 * Used in the post type actions for 'gigneo_freelancer' and 'gigneo_employer'.
	 *
	 * @param int    $post_id    The post ID.
	 * @param int    $author_id  The author (user) ID.
	 * @param string $post_type  The post type.
	 *
	 * @since 0.0.1
	 */
	public function post_type_actions( $post_id, $author_id, $post_type ) {
		if ( 'gigneo_freelancer' !== $post_type && 'gigneo_employer' !== $post_type ) {
			return;
		}
		$email_verified = get_user_meta( $author_id, '_gigneo_um_email_verified', true );
		$email_icon     = $email_verified ? GIGNEO_DIR_URL . 'assets/img/icon/email-verified.png' : GIGNEO_DIR_URL . 'assets/img/icon/email-unverified.png';
		$tooltip_text   = $email_verified ? esc_html__( 'Email Verified', 'gigneo' ) : esc_html__( 'Email unverified', 'gigneo' );
		?>
		<div class="gn-post-type-action gn-action-email-verification">
			<button type="button" data-gn-id="<?php echo esc_attr( $post_id ); ?>"
					data-gn-type="<?php echo esc_attr( $email_verified ? 'verified' : 'unverified' ); ?>"
					class="gn-email-verification-btn" data-gn-tooltip="<?php echo esc_attr( $tooltip_text ); ?>">
				<img src="<?php echo esc_url( $email_icon ); ?>"
					alt="<?php echo esc_html__( 'Email Verification', 'gigneo' ); ?>">
			</button>
		</div>
		<?php
	}
}
