<?php

namespace Gigneo;

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

use Carbon_Fields\Carbon_Fields;

/**
 * Class Core
 *
 * Plugin core class for Gigneo.
 *
 * @since 0.0.1
 */
class Core {

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

	/**
	 * Constructor for the class.
	 *
	 * @since 0.0.1
	 */
	public function __construct() {

		// Register carbon fields
		add_action( 'after_setup_theme', array( $this, 'boot_carbon_fields' ) );

		// Register roles
		add_action( 'init', array( $this, 'register_user_roles' ) );

		// Restrict admin access
		add_action( 'admin_init', array( $this, 'restrict_admin_access' ) );

		// Body class
		add_filter( 'body_class', array( $this, 'body_class' ) );

		// Register Menu
		add_action( 'admin_menu', array( $this, 'register_menu' ) );

		// Modify sub menu
		add_action( 'admin_menu', array( $this, 'modify_submenu' ), 20 );

		// Add auth popup
		add_action( 'wp_footer', array( $this, 'auth_popup_markup' ) );

		// Connect child menu to parent
		add_filter( 'parent_file', array( $this, 'menu_active_state' ) );

		// Template Include
		add_filter( 'template_include', array( $this, 'template_include' ) );

		// Modify the content
		add_filter( 'the_content', array( $this, 'modify_content' ) );

		// User profile column
		add_filter( 'manage_users_columns', array( $this, 'custom_column' ) );

		// User profile column content
		add_filter( 'manage_users_custom_column', array( $this, 'custom_column_content' ), 10, 3 );

		// Plugin action links
		add_filter( 'plugin_action_links_' . GIGNEO_BASE, array( $this, 'plugin_action_links' ) );

		//Plugin row meta
		add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );
	}

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

		return self::$instance;
	}

	/**
	 * Add settings link to the plugins page.
	 *
	 * @param array $links The existing plugin action links.
	 * @return array The updated plugin action links.
	 * @since 0.0.1
	 */
	public function plugin_action_links( $links ) {
		$settings_link = '<a href="' . admin_url( 'admin.php?page=gigneo-options' ) . '">' . esc_html__( 'Settings', 'gigneo' ) . '</a>';
		array_unshift( $links, $settings_link );

		return $links;
	}

	/**
	 * Add plugin row meta links.
	 *
	 * @param array  $plugin_meta The existing plugin row meta links.
	 * @param string $plugin_file The plugin file.
	 * @return array The updated plugin row meta links.
	 * @since 0.0.1
	 */
	public function plugin_row_meta( $plugin_meta, $plugin_file ) {
		if ( GIGNEO_BASE === $plugin_file ) {
			$row_meta    = array(
				'docs' => '<a href="https://gigneo.com/docs/freelance-service-marketplace/getting-started/introduction/" aria-label="' . esc_attr__( 'View Gigneo Documentation', 'gigneo' ) . '" target="_blank">' . esc_html__( 'Docs & FAQs', 'gigneo' ) . '</a>',
			);
			$plugin_meta = array_merge( $plugin_meta, $row_meta );
		}

		return $plugin_meta;
	}

	/**
	 * Register custom user roles for the plugin.
	 *
	 * This function adds the `freelancer`, `employer` and manager roles.
	 *
	 * @since 0.0.1
	 */
	public static function register_user_roles() {

		$freelancer_singular = gigneo_freelancer_singular();
		$employer_singular   = gigneo_employer_singular();

		// Get WooCommerce customer capabilities
		$customer_role = get_role( 'customer' );
		$caps          = $customer_role ? $customer_role->capabilities : array();

		// Your custom capabilities
		$custom_caps = array(
			'upload_files' => true,
		);

		// Merge capabilities (custom overrides customer if same key)
		$freelancer_caps = array_merge( $caps, $custom_caps );
		$employer_caps   = array_merge( $caps, $custom_caps );

		// Add Freelancer role
		add_role(
			'gigneo_freelancer',
			$freelancer_singular,
			$freelancer_caps
		);

		// Add Employer role
		add_role(
			'gigneo_employer',
			$employer_singular,
			$employer_caps
		);
	}

	/**
	 * Hide the admin bar for non-admin Gigneo users on the frontend.
	 *
	 * This function checks if the current user has any of the specified roles
	 * and hides the admin bar if they do.
	 *
	 * @since 0.0.1
	 */
	public function restrict_admin_access() {

		// Allow AJAX requests through — admin-ajax.php fires admin_init
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			return;
		}

		// Allow users with 'manage_options' (admins) and editors through
		if ( current_user_can( 'manage_options' ) ) {
			return;
		}

		// Define Gigneo user roles that should be blocked
		$restricted_roles = apply_filters( 'gigneo_restricted_admin_roles', array( 'gigneo_freelancer', 'gigneo_employer' ) );

		$user = wp_get_current_user();

		// Check if the current user has any restricted role
		$has_restricted_role = ! empty( array_intersect( $restricted_roles, $user->roles ) );

		if ( $has_restricted_role ) {
			// Redirect to the frontend dashboard (or homepage as fallback)
			$redirect_url = apply_filters( 'gigneo_admin_restricted_redirect', gigneo_dashboard_url() );

			wp_safe_redirect( $redirect_url );
			exit;
		}
	}

	/**
	 * Adds custom classes to the body element on the dashboard page.
	 *
	 * Adds `gn-dashboard` and optionally `gn-source-{source}` and `gn-ref-{source}-{ref}` classes
	 * if the current page is the dashboard template and relevant query parameters are present.
	 *
	 * @param array $classes Existing body classes.
	 * @return array Modified body classes.
	 * @since 0.0.1
	 */
	public function body_class( $classes ) {
		$dashboard_template = gigneo_option( '_gigneo_ts_template_dashboard' );
		if ( ! empty( $dashboard_template ) && is_page( $dashboard_template ) ) {

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

			$slugs = array(
				Post_Types::post_type_slug( 'gigneo_job' ) => 'job',
				Post_Types::post_type_slug( 'gigneo_service' ) => 'service',
			);

			$classes[] = 'gn-dashboard';

			if ( ! empty( $source ) ) {
				$classes[] = 'gn-source-' . ( $slugs[ $source ] ?? $source );
				if ( ! empty( $ref ) ) {
					$classes[] = 'gn-ref-' . ( $slugs[ $source ] ?? $source ) . '-' . $ref;
				}
			}
		}

		return $classes;
	}

	/**
	 * Register the admin menu.
	 *
	 * @since 0.0.1
	 */
	public function register_menu() {

		$platform_type   = gigneo_platform_type();
		$post_types_slug = Post_Types::post_type_slug();
		$taxonomies_slug = Taxonomies::taxonomy_slug();

		// Parent Menu
		add_menu_page(
			esc_html__( 'Gigneo', 'gigneo' ),
			esc_html__( 'Gigneo', 'gigneo' ),
			'manage_options',
			'gigneo',
			array( $this, 'general_template' ),
			GIGNEO_DIR_URL . 'assets/img/icon-white.png',
			30
		);

		// Submenu - General
		add_submenu_page(
			'gigneo',
			esc_html__( 'General', 'gigneo' ),
			esc_html__( 'General', 'gigneo' ),
			'manage_options',
			'gigneo',
			array( $this, 'general_template' ),
			1
		);

		// Submenu - Modules
		add_submenu_page(
			'gigneo',
			esc_html__( 'Modules', 'gigneo' ),
			esc_html__( 'Modules', 'gigneo' ),
			'manage_options',
			'gigneo-modules',
			array( $this, 'modules_template' ),
			5
		);

		// Submenu - Freelancer
		add_submenu_page(
			'gigneo',
			gigneo_freelancer_singular(),
			gigneo_freelancer_plural(),
			'manage_options',
			'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_freelancer'],
			'',
			10
		);

		// Submenu - Service
		if ( 'jobs' !== $platform_type ) {
			add_submenu_page(
				'gigneo',
				esc_html__( 'Service', 'gigneo' ),
				esc_html__( 'Services', 'gigneo' ),
				'manage_options',
				'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_service'],
				'',
				15
			);
		}

		// Submenu - Employer
		add_submenu_page(
			'gigneo',
			gigneo_employer_singular(),
			gigneo_employer_plural(),
			'manage_options',
			'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_employer'],
			'',
			20
		);

		// Submenu - Job
		if ( 'services' !== $platform_type ) {
			add_submenu_page(
				'gigneo',
				esc_html__( 'Job', 'gigneo' ),
				esc_html__( 'Jobs', 'gigneo' ),
				'manage_options',
				'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_job'],
				'',
				30
			);
		}

		// Submenu - Proposal
		if ( 'services' !== $platform_type ) {
			add_submenu_page(
				'gigneo',
				esc_html__( 'Proposal', 'gigneo' ),
				esc_html__( 'Proposals', 'gigneo' ),
				'manage_options',
				'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_proposal'],
				'',
				25
			);
		}

		// Submenu - Order
		add_submenu_page(
			'gigneo',
			esc_html__( 'Order', 'gigneo' ),
			esc_html__( 'Orders', 'gigneo' ),
			'manage_options',
			'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_order'],
			'',
			35
		);

		// Submenu - Invoice
		add_submenu_page(
			'gigneo',
			esc_html__( 'Invoice', 'gigneo' ),
			esc_html__( 'Invoices', 'gigneo' ),
			'manage_options',
			'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_invoice'],
			'',
			40
		);

		// Submenu - Withdraw
		add_submenu_page(
			'gigneo',
			esc_html__( 'Withdrawal', 'gigneo' ),
			esc_html__( 'Withdrawals', 'gigneo' ),
			'manage_options',
			'edit.php?post_type=gigneo_' . $post_types_slug['gigneo_withdrawal'],
			'',
			45
		);

		// Submenu - Category
		add_submenu_page(
			'gigneo',
			esc_html__( 'Category', 'gigneo' ),
			esc_html__( 'Categories', 'gigneo' ),
			'manage_options',
			'edit-tags.php?taxonomy=gigneo_' . $taxonomies_slug['gigneo_facet'],
			'',
			50
		);

		//Submenu - Skills
		add_submenu_page(
			'gigneo',
			esc_html__( 'Skill', 'gigneo' ),
			esc_html__( 'Skills', 'gigneo' ),
			'manage_options',
			'edit-tags.php?taxonomy=gigneo_' . $taxonomies_slug['gigneo_skill'],
			'',
			55
		);

		// Submenu - City
		$cities_option = gigneo_option( '_gigneo_ts_disable_cities', false );
		if ( ! $cities_option ) {
			add_submenu_page(
				'gigneo',
				esc_html__( 'City', 'gigneo' ),
				esc_html__( 'Cities', 'gigneo' ),
				'manage_options',
				'edit-tags.php?taxonomy=gigneo_' . $taxonomies_slug['gigneo_city'],
				'',
				60
			);
		}

		// Submenu - License
		add_submenu_page(
			'gigneo',
			esc_html__( 'License', 'gigneo' ),
			esc_html__( 'Licenses', 'gigneo' ),
			'manage_options',
			'edit-tags.php?taxonomy=gigneo_' . $taxonomies_slug['gigneo_license'],
			'',
			65
		);

		// Submenu - Language
		add_submenu_page(
			'gigneo',
			esc_html__( 'Language', 'gigneo' ),
			esc_html__( 'Languages', 'gigneo' ),
			'manage_options',
			'edit-tags.php?taxonomy=gigneo_' . $taxonomies_slug['gigneo_language'],
			'',
			70
		);

		// Add action for a custom menu
		do_action( 'gigneo_register_submenu', 'gigneo' );

		// Submenu - Tools
		add_submenu_page(
			'gigneo',
			esc_html__( 'Tools', 'gigneo' ),
			esc_html__( 'Tools', 'gigneo' ),
			'manage_options',
			'gigneo-tools',
			array( $this, 'tools_template' ),
			100
		);

	}

	/**
	 * Modify the submenu items.
	 *
	 * @since 0.0.1
	 */
	public function modify_submenu() {
		global $submenu;

		$menu_slug = 'gigneo';

		if ( isset( $submenu[ $menu_slug ] ) ) {
			foreach ( $submenu[ $menu_slug ] as $key => $menu_item ) {
				if ( 'gigneo-options' === $menu_item[2] ) {
					// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
					$submenu[ $menu_slug ][ $key ][0] = esc_html__( 'Settings', 'gigneo' );
				}
			}
		}
	}

	/**
	 * Set the active state for the admin menu.
	 *
	 * @param string $parent_file The parent file.
	 *
	 * @return string
	 * @since 0.0.1
	 */
	public function menu_active_state( $parent_file ) {
		global $submenu_file;

		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only parameters no nonce required.
		$post_type = isset( $_GET['post_type'] ) ? sanitize_text_field( wp_unslash( $_GET['post_type'] ) ) : '';
		$taxonomy  = isset( $_GET['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_GET['taxonomy'] ) ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended -- Read-only parameters no nonce required.

		if ( ! empty( $post_type ) ) {
			$post_type_slug = Post_Types::post_type_slug( $post_type );
			if ( ! empty( $post_type_slug ) ) {
				$submenu_file = "edit.php?post_type=gigneo_$post_type_slug"; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
				$parent_file  = 'gigneo';
			}
		}

		if ( ! empty( $taxonomy ) ) {
			$taxonomies_slug = Taxonomies::taxonomy_slug( $taxonomy );
			if ( ! empty( $taxonomies_slug ) ) {
				$submenu_file = "edit-tags.php?taxonomy=gigneo_$taxonomies_slug"; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
				$parent_file  = 'gigneo';
			}
		}

		return $parent_file;
	}

	/**
	 * Display the general template.
	 *
	 * @since 0.0.1
	 */
	public function general_template() {
		gigneo_load_template( 'admin/general.php' );
	}

	/**
	 * Display the module template.
	 *
	 * @since 0.0.1
	 */
	public function modules_template() {
		gigneo_load_template( 'admin/modules.php' );
	}

	/**
	 * Display the setting template.
	 *
	 * @since 0.0.1
	 */
	public function tools_template() {
		gigneo_load_template( 'admin/tools.php' );
	}

	/**
	 * Include custom templates for the plugin.
	 *
	 * This function includes custom templates for the plugin.
	 *
	 * @param string $template Template file.
	 *
	 * @return string
	 * @since 0.0.1
	 */
	public function template_include( $template ) {

		// Dashboard
		$dashboard_template = gigneo_option( '_gigneo_ts_template_dashboard' );

		if ( ! empty( $dashboard_template ) && is_page( $dashboard_template ) ) {
			$new_template = gigneo_get_template( 'dashboard/general' );
			if ( file_exists( $new_template ) ) {
				return $new_template;
			}
		}

		return $template;
	}

	public function modify_content( $content ) {

		if ( in_the_loop() && is_main_query() && is_singular( 'gigneo_service' ) ) {
			ob_start();
			gigneo_load_template( 'single/service/layout-1' );
			$custom_content = ob_get_clean();

			$content .= $custom_content;
		} elseif ( in_the_loop() && is_main_query() && is_singular( 'gigneo_job' ) ) {
			ob_start();
			gigneo_load_template( 'single/job/layout-1' );
			$custom_content = ob_get_clean();

			$content .= $custom_content;
		} elseif ( in_the_loop() && is_main_query() && is_singular( 'gigneo_freelancer' ) ) {
			ob_start();
			gigneo_load_template( 'single/profile/layout-1' );
			$custom_content = ob_get_clean();

			$content .= $custom_content;
		} elseif ( in_the_loop() && is_main_query() && is_singular( 'gigneo_employer' ) ) {
			$employer_profile_access = gigneo_employer_profile_access();
			if ( 'public' === $employer_profile_access ) {
				ob_start();
				gigneo_load_template( 'single/profile/layout-1' );
				$custom_content = ob_get_clean();

				$content .= $custom_content;
			}
		}

		return $content;
	}

	/**
	 * Add the authentication popup markup to the footer.
	 *
	 * This function includes the authentication popup template in the footer.
	 *
	 * @since 0.0.1
	 */
	public function auth_popup_markup() {
		$enable_popup = gigneo_option( '_gigneo_ts_auth_popup' );

		$login_template           = gigneo_option( '_gigneo_ts_template_login' );
		$register_template        = gigneo_option( '_gigneo_ts_template_register' );
		$forgot_password_template = gigneo_option( '_gigneo_ts_template_forgot_password' );

		$excluded_pages = array_filter( array( $login_template, $register_template, $forgot_password_template ) );

		if ( ! is_user_logged_in() && $enable_popup && ( empty( $excluded_pages ) || ! is_page( $excluded_pages ) ) ) {
			gigneo_load_template( 'auth/popup' );
		}
	}

	/**
	 * Boots the Carbon Fields library.
	 *
	 * @since 0.0.1
	 */
	public function boot_carbon_fields() {

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only parameters no nonce required.
		$action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';

		if ( ! class_exists( 'Carbon_Fields\Carbon_Fields' ) ) {
			return;
		}

		if ( 'elementor' === $action ) {
			return;
		}

		Carbon_Fields::boot();
	}

	public function custom_column( $columns ) {
		$new_columns = array();

		foreach ( $columns as $key => $label ) {
			$new_columns[ $key ] = $label;

			if ( 'role' === $key ) {
				$new_columns['gigneo_actions'] = __( 'Actions', 'gigneo' );
			}
		}

		return $new_columns;
	}

	public function custom_column_content( $value, $column_name, $user_id ) {
		if ( 'gigneo_actions' !== $column_name ) {
			return $value;
		}

		$user_id = absint( $user_id );

		$freelancer_profile_id = absint(
			get_user_meta( $user_id, '_gigneo_um_freelancer_profile_id', true )
		);

		$employer_profile_id = absint(
			get_user_meta( $user_id, '_gigneo_um_employer_profile_id', true )
		);

		$active_profile  = get_user_meta( $user_id, '_gigneo_um_active_profile', true );
		$default_profile = get_user_meta( $user_id, '_gigneo_um_default_profile', true );

		$classes = "gn-user-action gn-active-profile- $active_profile gn-default-profile- $default_profile";

		$output = '<div class="' . esc_attr( $classes ) . '">';

		$profiles = array(
			array(
				'id'         => $freelancer_profile_id,
				'label'      => gigneo_freelancer_singular(),
				'type'       => 'freelancer',
				'create_cls' => 'gn-create-freelancer-profile',
				'exist_icon' => GIGNEO_DIR_URL . 'assets/img/icon/freelancer-exist.png',
				'empty_icon' => GIGNEO_DIR_URL . 'assets/img/icon/freelancer-not-exist.png',
			),
			array(
				'id'         => $employer_profile_id,
				'label'      => gigneo_employer_singular(),
				'type'       => 'employer',
				'create_cls' => 'gn-create-employer-profile',
				'exist_icon' => GIGNEO_DIR_URL . 'assets/img/icon/employer-exist.png',
				'empty_icon' => GIGNEO_DIR_URL . 'assets/img/icon/employer-not-exist.png',
			),
		);

		foreach ( $profiles as $profile ) {
			$profile_id = absint( $profile['id'] );
			$type       = sanitize_key( $profile['type'] );

			if ( $profile_id ) {

				$tooltip = sprintf(
				// translators: %s: Profile label.
					esc_html__( 'Visit %s Profile', 'gigneo' ),
					esc_html( $profile['label'] )
				);

				$output .= '<a href="' . esc_url( admin_url( 'post.php?post=' . $profile_id . '&action=edit' ) ) . '" 
				class="gn-user-profile-btn gn-' . esc_attr( $type ) . '-profile-btn" 
				data-gn-tooltip="' . esc_attr( $tooltip ) . '">
				<img src="' . esc_url( $profile['exist_icon'] ) . '" alt="' . esc_attr__( 'Profile', 'gigneo' ) . '">
			</a>';

			} else {

				$tooltip = sprintf(
				// translators: %s: Profile label.
					esc_html__( 'Create %s Profile', 'gigneo' ),
					esc_html( $profile['label'] )
				);

				$output .= '<button type="button" 
				class="gn-user-profile-btn gn-' . esc_attr( $type ) . '-profile-btn ' . esc_attr( $profile['create_cls'] ) . '" 
				data-gn-id="' . esc_attr( $user_id ) . '" 
				data-gn-tooltip="' . esc_attr( $tooltip ) . '">
				<img src="' . esc_url( $profile['empty_icon'] ) . '" alt="' . esc_attr__( 'Profile', 'gigneo' ) . '">
			</button>';
			}
		}

		$output .= '</div>';

		return $output;
	}
}
