<?php

namespace Gigneo\Modules;

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

use WP_User;

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

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

	/**
	 * Ensures only one instance of the class is loaded or can be loaded.
	 *
	 * @return Switch_Role
	 * @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() {
		//Switch profile ajax
		add_action( 'wp_ajax_gigneo_switch_profile', array( $this, 'switch_profile' ) );

		//Add active role field
		add_action( 'show_user_profile', array( $this, 'add_active_profile_field' ), 20 );
		add_action( 'edit_user_profile', array( $this, 'add_active_profile_field' ), 20 );

		//Save active role field
		add_action( 'personal_options_update', array( $this, 'save_active_profile_field' ) );
		add_action( 'edit_user_profile_update', array( $this, 'save_active_profile_field' ) );
	}

	/**
	 * Switch the user profile type.
	 *
	 * This function handles the AJAX request to switch the user's profile type
	 * between freelancer and employer. It checks for the required capabilities,
	 * creates a new profile if necessary, and updates the user's active profile.
	 *
	 * @since 0.0.1
	 */
	public function switch_profile() {

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

		$current_user_id     = get_current_user_id();
		$has_platform_access = gigneo_user_have_access();

		// Ensure the user has proper access.
		if ( empty( $current_user_id ) || ! $has_platform_access ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'You do not have permission to perform this action.', 'gigneo' ) ),
				403
			);
		}

		$user         = new WP_User( $current_user_id );
		$profile_type = gigneo_profile_type();

		// Validate profile type.
		if ( ! in_array( $profile_type, array( 'freelancer', 'employer' ), true ) ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'Invalid profile type.', 'gigneo' ) ),
				403
			);
		}

		// Determine target profile type (the one to switch to).
		$target_type = ( 'freelancer' === $profile_type ) ? 'employer' : 'freelancer';

		// Assign missing capability if not present.
		$required_cap = 'gigneo_' . $target_type;
		$user->add_cap( $required_cap );

		// Retrieve or create target profile.
		$meta_key = ( 'freelancer' === $target_type )
			? '_gigneo_um_freelancer_profile_id'
			: '_gigneo_um_employer_profile_id';

		$profile_id   = get_user_meta( $current_user_id, $meta_key, true );
		$profile_post = get_post( $profile_id );

		if ( empty( $profile_id ) || ! $profile_post ) {
			$profile_id   = gigneo_create_profile( $current_user_id, $target_type );
			$profile_post = get_post( $profile_id );
		}

		// Validate new profile.
		if ( empty( $profile_id ) || ! $profile_post ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'Unable to switch profile at this time.', 'gigneo' ) ),
				500
			);
		}

		// Update active profile meta.
		update_user_meta( $current_user_id, '_gigneo_um_active_profile', $target_type );

		// Prepare redirect to dashboard.
		$dashboard_page_id = gigneo_option( '_gigneo_ts_template_dashboard' );
		$redirect_url      = $dashboard_page_id ? get_permalink( $dashboard_page_id ) : home_url();

		wp_send_json_success(
			array(
				'message'  => esc_html__( 'Profile successfully switched.', 'gigneo' ),
				'redirect' => esc_url_raw( $redirect_url ),
			)
		);
	}

	public function add_active_profile_field( $user ) {
		if ( empty( $user->ID ) ) {
			return;
		}

		if ( ! $user->has_cap( 'gigneo_freelancer' ) && ! $user->has_cap( 'gigneo_employer' ) ) {
			return;
		}

		include GIGNEO_DIR_PATH . 'includes/switch-role/views/role-field.php';
	}

	public function save_active_profile_field( $user_id ) {

		$nonce = isset( $_POST['gigneo_switch_role_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['gigneo_switch_role_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'gigneo_switch_role' ) ) {
			return false;
		}

		if ( ! current_user_can( 'edit_user', $user_id ) ) {
			return false;
		}

		$active_profile = isset( $_POST['gigneo_active_profile'] ) ? sanitize_text_field( wp_unslash( $_POST['gigneo_active_profile'] ) ) : '';
		if ( ! empty( $active_profile ) && in_array( $active_profile, array( 'freelancer', 'employer' ), true ) ) {
			update_user_meta( $user_id, '_gigneo_um_active_profile', $active_profile );
		}
	}
}
