<?php

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

use Automattic\WooCommerce\Utilities\FeaturesUtil;
use Gigneo\Emails\Account_Activated;
use Gigneo\Emails\Account_Closed;
use Gigneo\Emails\Account_Deactivated;
use Gigneo\Emails\Account_Reactivated;
use Gigneo\Emails\Email_Verification;
use Gigneo\Emails\Service_Approved;
use Gigneo\Emails\Service_Cancel_Request;
use Gigneo\Emails\Service_Cancel_Response;
use Gigneo\Emails\Service_Cancelled;
use Gigneo\Emails\Service_Completed;
use Gigneo\Emails\Service_Delivered;
use Gigneo\Emails\Service_Hired;
use Gigneo\Emails\Service_Moderator_Cancelled;
use Gigneo\Emails\Service_Moderator_Completed;
use Gigneo\Emails\Service_Published;
use Gigneo\Emails\Service_Rejected;
use Gigneo\Emails\Service_Requested;
use Gigneo\Emails\Service_Review;
use Gigneo\Emails\Service_Revision;
use Gigneo\Emails\User_Registration;
use Gigneo\Emails\Withdraw_Request;
use Gigneo\Emails\Withdraw_Response;
use Gigneo\Emails\Job_Requested;
use Gigneo\Emails\Job_Approved;
use Gigneo\Emails\Job_Published;
use Gigneo\Emails\Job_Rejected;
use Gigneo\Emails\Job_Proposal_Submitted;
use Gigneo\Emails\Job_Hired;
use Gigneo\Emails\Job_Delivered;
use Gigneo\Emails\Job_Revision;
use Gigneo\Emails\Job_Completed;
use Gigneo\Emails\Job_Cancelled;
use Gigneo\Emails\Job_Review;
use Gigneo\Emails\Job_Cancel_Request;
use Gigneo\Emails\Job_Cancel_Response;
use Gigneo\Emails\Job_Moderator_Completed;
use Gigneo\Emails\Job_Moderator_Cancelled;
use Gigneo\Notifications;

/**
 * Update the user's last activity timestamp.
 *
 * This function updates the last activity timestamp for the logged-in user.
 *
 * @since 0.0.1
 */
function gigneo_update_user_last_activity() {
	if ( is_user_logged_in() ) {
		$profile_id = gigneo_active_profile_id();
		update_post_meta( $profile_id, '_gigneo_pm_last_activity', time() );

		//Offline for
		$offline_until = gigneo_post_meta( $profile_id, '_gigneo_pm_offline_until' );
		if ( ! empty( $offline_until ) || 'forever' !== $offline_until ) {
			$now = time();
			if ( is_numeric( $offline_until ) && $now >= intval( $offline_until ) ) {
				delete_post_meta( $profile_id, '_gigneo_pm_offline_until' );
			}
		}
	}
}
// Add the action to update the user's last activity timestamp.
add_action( 'init', 'gigneo_update_user_last_activity' );

/**
 * Set post state.
 *
 * This function sets the post state for the plugin's custom templates.
 *
 * @param array $post_states The array of post states.
 * @param object $post The post object.
 *
 * @return array The array of post states.
 * @since 0.0.1
 */
function gigneo_set_post_state( $post_states, $post ) {
	$dashboard_template       = gigneo_option( '_gigneo_ts_template_dashboard' );
	$hire_template            = gigneo_option( '_gigneo_ts_template_hire' );
	$contact_template         = gigneo_option( '_gigneo_ts_template_contact' );
	$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' );
	$freelancer_template      = gigneo_option( '_gigneo_ts_template_freelancers' );
	$service_template         = gigneo_option( '_gigneo_ts_template_services' );
	$employer_template        = gigneo_option( '_gigneo_ts_template_employers' );
	$job_template             = gigneo_option( '_gigneo_ts_template_jobs' );
	$wallet_product           = gigneo_option( '_gigneo_ts_wallet_product' );
	$withdrawal_product       = gigneo_option( '_gigneo_ts_withdrawal_product' );

	//Dashboards
	if ( ! empty( $dashboard_template ) && 'page' === $post->post_type && intval( $dashboard_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Dashboard', 'gigneo' );
	}

	//Hire
	if ( ! empty( $hire_template ) && 'page' === $post->post_type && intval( $hire_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Hire', 'gigneo' );
	}

	//Contact
	if ( ! empty( $contact_template ) && 'page' === $post->post_type && intval( $contact_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Contact', 'gigneo' );
	}

	//Login and Register
	if ( ! empty( $login_template ) && 'page' === $post->post_type && intval( $login_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Login', 'gigneo' );
	}

	if ( ! empty( $register_template ) && 'page' === $post->post_type && intval( $register_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Register', 'gigneo' );
	}

	if ( ! empty( $forgot_password_template ) && 'page' === $post->post_type && intval( $forgot_password_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Forgot Password', 'gigneo' );
	}

	//Archives
	if ( ! empty( $freelancer_template ) && 'page' === $post->post_type && intval( $freelancer_template ) === $post->ID ) {
		$post_states[] = sprintf(
			// translators: %s is freelancer singular
			esc_html__( 'Gigneo %s', 'gigneo' ),
			gigneo_freelancer_plural()
		);
	}

	if ( ! empty( $service_template ) && 'page' === $post->post_type && intval( $service_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Services', 'gigneo' );
	}

	if ( ! empty( $employer_template ) && 'page' === $post->post_type && intval( $employer_template ) === $post->ID ) {
		$post_states[] = sprintf(
			// translators: %s is employer singular
			esc_html__( 'Gigneo %s', 'gigneo' ),
			gigneo_employer_plural()
		);
	}

	if ( ! empty( $job_template ) && 'page' === $post->post_type && intval( $job_template ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Jobs', 'gigneo' );
	}

	//Products
	if ( ! empty( $wallet_product ) && 'product' === $post->post_type && intval( $wallet_product ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Wallet', 'gigneo' );
	}
	if ( ! empty( $withdrawal_product ) && 'product' === $post->post_type && intval( $withdrawal_product ) === $post->ID ) {
		$post_states[] = esc_html__( 'Gigneo Withdrawal', 'gigneo' );
	}

	return $post_states;
}
// Add the filter to set the post-state for custom templates.
add_filter( 'display_post_states', 'gigneo_set_post_state', 10, 2 );

/**
 * Hide the admin bar for specific user roles.
 *
 * @param $show
 *
 * @return bool Whether to show the admin bar.
 * @since 0.0.1
 */
function gigneo_hide_admin_bar( $show ) {
	$user = wp_get_current_user();

	$show_for_freelancers = get_option( '_gigneo_freelancer_show_toolbar', false );
	$show_for_employers   = get_option( '_gigneo_employer_show_toolbar', false );

	// phpcs:ignore WordPress.WP.Capabilities.Unknown -- Registered capabilities
	if ( user_can( $user->ID, 'gigneo_freelancer' ) ) {
		return $show_for_freelancers;
	}

	// phpcs:ignore WordPress.WP.Capabilities.Unknown -- Registered capabilities
	if ( user_can( $user->ID, 'gigneo_employer' ) ) {
		return $show_for_employers;
	}

	return $show;
}
// Add the filter to hide the admin bar for specific user roles.
add_filter( 'show_admin_bar', 'gigneo_hide_admin_bar' );

/**
 * Update the service count for a freelancer when a service is saved.
 *
 * This function updates the service count for a freelancer when a service is saved.
 *
 * @param int $post_id The ID of the post being saved.
 * @since 0.0.1
 */
function gigneo_update_service_count( $post_id ) {

	if ( get_post_type( $post_id ) !== 'gigneo_service' ) {
		return;
	}

	// Get the post author ID
	$author_id = get_post_field( 'post_author', $post_id );

	if ( ! $author_id ) {
		return;
	}

	// Get the freelancer profile ID
	$freelancer_id = gigneo_profile_id( $author_id, 'freelancer' );

	if ( ! $freelancer_id ) {
		return;
	}

	$args = array(
		'post_type'      => 'gigneo_service',
		'post_status'    => 'publish',
		'author'         => $author_id,
		'fields'         => 'ids',
		'posts_per_page' => -1,
		'no_found_rows'  => true,
	);

	$service_posts = get_posts( $args );

	// Count all published services
	$service_count = count( $service_posts );

	// Update the freelancer's custom field with the service count
	update_post_meta( $freelancer_id, '_gigneo_published_services', $service_count );
}
// Add the action to update the service count when a service is saved.
add_action( 'save_post', 'gigneo_update_service_count' );
add_action( 'trashed_post', 'gigneo_update_service_count' );
add_action( 'untrashed_post', 'gigneo_update_service_count' );
add_action( 'before_delete_post', 'gigneo_update_service_count' );

/**
 * Register custom email classes for WooCommerce.
 *
 * @param array $email_classes Existing email classes.
 * @return array Modified email classes with custom emails.
 * @since 0.0.1
 */
function gigneo_register_emails( $email_classes ) {

	$platform_type         = gigneo_platform_type();
	$service_admin_approve = gigneo_option( '_gigneo_ts_service_manually_approve', false );
	$job_admin_approve     = gigneo_option( '_gigneo_ts_job_manually_approve', false );

	//User Registration
	$email_classes['Gigneo_User_Registration'] = new User_Registration();

	//Email Verification
	if ( in_array( 'email_verification', gigneo_active_modules(), true ) ) {
		$email_classes['Gigneo_Email_Verification'] = new Email_Verification();
	}

	//Account Activation/Deactivation
	if ( in_array( 'deactivate_account', gigneo_active_modules(), true ) ) {
		$email_classes['Gigneo_Account_Deactivated'] = new Account_Deactivated();
		$email_classes['Gigneo_Account_Activated']   = new Account_Activated();
	}

	//Account Closed
	if ( in_array( 'close_account', gigneo_active_modules(), true ) ) {
		$email_classes['Gigneo_Account_Closed'] = new Account_Closed();
	}

	if ( in_array( 'close_account', gigneo_active_modules(), true ) || in_array( 'block_account', gigneo_active_modules(), true ) ) {
		$email_classes['Gigneo_Account_Reactivated'] = new Account_Reactivated();
	}

	//Services Emails
	if ( 'job' !== $platform_type ) {

		if ( $service_admin_approve ) {
			$email_classes['Gigneo_Service_Requested'] = new Service_Requested();
			$email_classes['Gigneo_Service_Approved']  = new Service_Approved();
			$email_classes['Gigneo_Service_Rejected']  = new Service_Rejected();
		} else {
			$email_classes['Gigneo_Service_Published'] = new Service_Published();
		}

		$email_classes['Gigneo_Service_Hired']               = new Service_Hired();
		$email_classes['Gigneo_Service_Delivered']           = new Service_Delivered();
		$email_classes['Gigneo_Service_Revision']            = new Service_Revision();
		$email_classes['Gigneo_Service_Completed']           = new Service_Completed();
		$email_classes['Gigneo_Service_Cancelled']           = new Service_Cancelled();
		$email_classes['Gigneo_Service_Review']              = new Service_Review();
		$email_classes['Gigneo_Service_Cancel_Request']      = new Service_Cancel_Request();
		$email_classes['Gigneo_Service_Cancel_Response']     = new Service_Cancel_Response();
		$email_classes['Gigneo_Service_Moderator_Completed'] = new Service_Moderator_Completed();
		$email_classes['Gigneo_Service_Moderator_Cancelled'] = new Service_Moderator_Cancelled();
		$email_classes['Gigneo_Withdraw_Request']            = new Withdraw_Request();
		$email_classes['Gigneo_Withdraw_Response']           = new Withdraw_Response();

	}
	if ( 'service' !== $platform_type ) {

		if ( $job_admin_approve ) {
			$email_classes['Gigneo_Job_Requested'] = new Job_Requested();
			$email_classes['Gigneo_Job_Approved']  = new Job_Approved();
			$email_classes['Gigneo_Job_Rejected']  = new Job_Rejected();
		} else {
			$email_classes['Gigneo_Job_Published'] = new Job_Published();
		}

		$email_classes['Gigneo_Job_Proposal_Submitted']  = new Job_Proposal_Submitted();
		$email_classes['Gigneo_Job_Hired']               = new Job_Hired();
		$email_classes['Gigneo_Job_Delivered']           = new Job_Delivered();
		$email_classes['Gigneo_Job_Revision']            = new Job_Revision();
		$email_classes['Gigneo_Job_Completed']           = new Job_Completed();
		$email_classes['Gigneo_Job_Cancelled']           = new Job_Cancelled();
		$email_classes['Gigneo_Job_Review']              = new Job_Review();
		$email_classes['Gigneo_Job_Cancel_Request']      = new Job_Cancel_Request();
		$email_classes['Gigneo_Job_Cancel_Response']     = new Job_Cancel_Response();
		$email_classes['Gigneo_Job_Moderator_Completed'] = new Job_Moderator_Completed();
		$email_classes['Gigneo_Job_Moderator_Cancelled'] = new Job_Moderator_Cancelled();

	}

	return $email_classes;
}
// Add the filter to register custom email classes.
add_filter( 'woocommerce_email_classes', 'gigneo_register_emails' );

/**
 * Declare WooCommerce compatibility features.
 *
 * This function declares compatibility for specific WooCommerce features.
 *
 * @since 0.0.1
 */
function gigneo_declare_woocommerce_compatibility() {
	if ( class_exists( FeaturesUtil::class ) ) {
		FeaturesUtil::declare_compatibility( 'custom_order_tables', GIGNEO_FILE );
		FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', GIGNEO_FILE );
		FeaturesUtil::declare_compatibility( 'hpos', GIGNEO_FILE );
	}
}
// Add the action to declare WooCommerce compatibility features.
add_action( 'before_woocommerce_init', 'gigneo_declare_woocommerce_compatibility' );



/**
 * Adjust the cart item price based on a custom amount.
 *
 * This function adjusts the cart item price based on a custom amount stored in the cart item data.
 *
 * @param WC_Cart $cart The WooCommerce cart object.
 * @since 0.0.1
 */
function gigneo_adjust_cart_item_price( $cart ) {
	if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
		return;
	}
	if ( $cart->is_empty() ) {
		return;
	}

	foreach ( $cart->get_cart() as $cart_item ) {
		if ( isset( $cart_item['wallet_amount'] ) ) {
			$custom_amount = absint( $cart_item['wallet_amount'] );
			if ( $custom_amount > 0 ) {
				$cart_item['data']->set_price( $custom_amount );
			}
		}
	}
}
// Add the action to adjust the cart item price.
add_action( 'woocommerce_before_calculate_totals', 'gigneo_adjust_cart_item_price' );


/**
 * Filter the display label for custom order item meta.
 *
 * This function renames the meta key 'wallet_amount' to a more user-friendly label
 * 'Wallet Amount' on the WooCommerce order received page and related views.
 *
 * @param string                $key_label The meta key label to be displayed.
 * @param WC_Meta_Data          $meta      Meta data object containing key and value.
 * @param WC_Order_Item_Product $item      The order item object.
 *
 * @return string Modified meta key label.
 * @since 0.0.1
 */
function gigneo_order_item_meta_key( $key_label, $meta, $item ) {
	if ( 'wallet_amount' === $meta->key ) {
		$key_label = esc_html__( 'Wallet Amount', 'gigneo' );
	}
	return $key_label;
}

add_filter( 'woocommerce_order_item_display_meta_key', 'gigneo_order_item_meta_key', 10, 3 );

/**
 * Add wallet meta to order item.
 *
 * This function adds wallet meta to the order item when creating an order.
 *
 * @param WC_Order_Item_Product $item The order item object.
 * @param string $cart_item_key The cart item key.
 * @param array $values The cart item values.
 * @since 0.0.1
 */
function gigneo_add_wallet_meta_to_order_item( $item, $cart_item_key, $values ) {
	if ( isset( $values['wallet_amount'] ) ) {
		$item->add_meta_data( 'wallet_amount', $values['wallet_amount'], true );
	}
}
// Add the action to add wallet meta to order item.
add_action( 'woocommerce_checkout_create_order_line_item', 'gigneo_add_wallet_meta_to_order_item', 10, 3 );

/**
 * Handle order invoice lifecycle.
 *
 * @param int      $order_id   Order ID.
 * @param string   $old_status Old status.
 * @param string   $new_status New status.
 * @param WC_Order $order      Order object.
 * @since 0.0.1
 */
function gigneo_handle_order_invoice_lifecycle( $order_id, $old_status, $new_status, $order ) {

	if ( ! $order instanceof WC_Order ) {
		$order = wc_get_order( $order_id );
	}

	if ( ! $order ) {
		return;
	}

	$invoice_id = $order->get_meta( '_gigneo_pm_invoice_id' );

	// Create invoice once.
	if ( ! $invoice_id ) {

		$total_wallet_funds = 0;

		foreach ( $order->get_items( 'line_item' ) as $item ) {

			$amount = $item->get_meta( 'wallet_amount' );

			if ( is_numeric( $amount ) ) {
				$total_wallet_funds += (float) $amount;
			}
		}

		if ( $total_wallet_funds > 0 ) {

			$invoice_id = wp_insert_post(
				array(
					'post_type'   => 'gigneo_invoice',
					'post_status' => 'publish',
					'post_title'  => esc_html__( 'Wallet Deposit', 'gigneo' ),
					'post_author' => $order->get_user_id(),
				)
			);

			if ( ! is_wp_error( $invoice_id ) ) {

				$active_profile_id = gigneo_active_profile_id( $order->get_user_id() );

				update_post_meta( $invoice_id, '_gigneo_pm_type', 'wallet' );
				update_post_meta( $invoice_id, '_gigneo_pm_profile_id', $active_profile_id );
				update_post_meta( $invoice_id, '_gigneo_pm_order_id', $order_id );
				update_post_meta( $invoice_id, '_gigneo_pm_total', $total_wallet_funds );
				update_post_meta( $invoice_id, '_gigneo_pm_tax', $order->get_total_tax() );

				$order->update_meta_data( '_gigneo_pm_invoice_id', $invoice_id );
				$order->update_meta_data( '_gigneo_pm_wallet_amount', $total_wallet_funds );
				$order->update_meta_data( '_gigneo_pm_profile_id', $active_profile_id );

				$order->save();
			}
		}
	}

	// Sync statuses.
	if (
		$invoice_id &&
		'gigneo_invoice' === get_post_type( $invoice_id ) &&
		$old_status !== $new_status &&
		'refunded' !== $new_status
	) {
		wp_update_post(
			array(
				'ID'          => $invoice_id,
				'post_status' => $new_status,
			)
		);
	}

	// Completed notification.
	if ( 'completed' === $new_status && $invoice_id ) {

		$active_profile_id  = get_post_meta( $invoice_id, '_gigneo_pm_profile_id', true );
		$linked_order_id    = get_post_meta( $invoice_id, '_gigneo_pm_order_id', true );
		$total_wallet_funds = get_post_meta( $invoice_id, '_gigneo_pm_total', true );

		Notifications::trigger_notification(
			'Funds added',
			sprintf(
				'The amount %s has been successfully added to your wallet.',
				gigneo_price_format( (float) $total_wallet_funds, true )
			),
			'wallet',
			'funds_added',
			$active_profile_id,
			$linked_order_id
		);
	}
}
add_action( 'woocommerce_order_status_changed', 'gigneo_handle_order_invoice_lifecycle', 10, 4 );

/**
 * Handle wallet invoice refunds.
 *
 * @param int $order_id  Order ID.
 * @param int $refund_id Refund ID.
 * @since 0.0.1
 */
function gigneo_handle_wallet_invoice_refund( $order_id, $refund_id ) {

	$order  = wc_get_order( $order_id );
	$refund = wc_get_order( $refund_id );

	if ( ! $order || ! $refund ) {
		return;
	}

	$invoice_id = $order->get_meta( '_gigneo_pm_invoice_id' );

	if ( ! $invoice_id || 'gigneo_invoice' !== get_post_type( $invoice_id ) ) {
		return;
	}

	// Original wallet deposit amount.
	$wallet_total = (float) get_post_meta(
		$invoice_id,
		'_gigneo_pm_total',
		true
	);

	if ( $wallet_total <= 0 ) {
		return;
	}

	$refund_amount = abs( (float) $refund->get_amount() );

	if ( $refund_amount <= 0 ) {
		return;
	}

	$already_refunded = (float) get_post_meta(
		$invoice_id,
		'_gigneo_pm_refunded',
		true
	);

	// Prevent refunding more than available.
	$wallet_refund = min(
		$refund_amount,
		$wallet_total - $already_refunded
	);

	$new_refunded_total = $already_refunded + $wallet_refund;

	$remaining_amount = max(
		0,
		$wallet_total - $new_refunded_total
	);

	update_post_meta(
		$invoice_id,
		'_gigneo_pm_refunded',
		$new_refunded_total
	);

	update_post_meta(
		$invoice_id,
		'_gigneo_pm_total',
		$remaining_amount
	);

	// Store remaining balance on order.
	$order->update_meta_data(
		'_gigneo_pm_wallet_amount',
		$remaining_amount
	);

	$order->save();

	// Fully refunded.
	if ( 0 >= $remaining_amount ) {

		wp_update_post(
			array(
				'ID'          => $invoice_id,
				'post_status' => 'refunded',
			)
		);
	}

	$active_profile_id = (int) get_post_meta(
		$invoice_id,
		'_gigneo_pm_profile_id',
		true
	);

	Notifications::trigger_notification(
		'Funds refunded',
		sprintf(
			'%s has been refunded from your wallet.',
			gigneo_price_format( $wallet_refund, true )
		),
		'wallet',
		'funds_refunded',
		$active_profile_id,
		$order_id
	);
}
add_action( 'woocommerce_order_refunded', 'gigneo_handle_wallet_invoice_refund', 10, 2 );

/**
 * Filter email recipients to block emails for withdrawal product orders.
 *
 * If the order contains the configured withdrawal product, return an empty
 * recipient string so WooCommerce will not send the email.
 *
 * @param string $recipient Current recipient(s) for the email.
 * @param WC_Order|int|null $order WC_Order object, order ID, or null.
 *
 * @return string Modified recipient string (empty to prevent sending).
 * @since 0.0.1
 */
function gigneo_disable_withdrawal_emails( $recipient, $order ) {
	if ( ! $order instanceof WC_Order ) {
		return $recipient;
	}

	$withdraw_id = (int) get_option( '_gigneo_ts_withdrawal_product' );

	if ( $withdraw_id ) {
		foreach ( $order->get_items( 'line_item' ) as $item ) {
			$pid = $item->get_product_id();
			if ( $pid === $withdraw_id ) {
				return ''; // disable email
			}
		}
	}

	return $recipient;
}

add_filter( 'woocommerce_email_recipient_customer_completed_order', 'gigneo_disable_withdrawal_emails', 10, 2 );

/**
 * Filter the post query to search by post id'.
 * @param $query
 *
 * @return void
 */

function gigneo_search_by_post_id( $query ) {
	if ( is_admin() && $query->is_main_query() && $query->is_search ) {

		$search = trim( $query->query_vars['s'] );

		// If the search query is a number, treat it as a post ID
		if ( is_numeric( $search ) ) {

			$query->set( 'post__in', array( intval( $search ) ) );
			$query->set( 's', '' ); // clear normal text search
		}
	}
}
add_action( 'pre_get_posts', 'gigneo_search_by_post_id' );

/**
 * Sync the order status with the invoice status.
 *
 * This function syncs the order status with the invoice status when the invoice status changes.
 *
 * @param string $new_status The new post status.
 * @param string $old_status The old post status.
 * @param WP_Post $post The post object.
 * @since 0.0.1
 */
function gigneo_sync_order_status_with_invoice_status( $new_status, $old_status, $post ) {
	if ( 'gigneo_invoice' !== $post->post_type || $new_status === $old_status ) {
		return;
	}

	$order_id = gigneo_post_meta( $post->ID, '_gigneo_pm_order_id' );
	if ( ! $order_id ) {
		return;
	}

	$order = wc_get_order( $order_id );
	if ( ! $order ) {
		return;
	}

	$status_map = array(
		'completed' => 'completed',
		'refunded'  => 'refunded',
		'cancelled' => 'cancelled',
		'failed'    => 'failed',
		'on-hold'   => 'on-hold',
		'pending'   => 'pending',
		'draft'     => 'draft',
		'publish'   => 'processing',
	);

	if ( isset( $status_map[ $new_status ] ) ) {
		$new_order_status = $status_map[ $new_status ];

		$current_order_status = $order->get_status();
		if ( $current_order_status !== $new_order_status ) {
			$order->update_status( $new_order_status, "Synced from invoice #{$post->ID}." );
		}
	}
}
// Add the action to sync order status with invoice status.
add_action( 'transition_post_status', 'gigneo_sync_order_status_with_invoice_status', 10, 3 );

/**
 * Prevent admin access for non-admin users.
 *
 * This function prevents admin access for non-admin users in WooCommerce.
 *
 * @param bool $prevent_access Whether to prevent access.
 * @return bool Whether to prevent access.
 * @since 0.0.1
 */
function gigneo_woocommerce_prevent_admin_access( $prevent_access ) {
	if ( gigneo_user_have_access() && current_user_can( 'upload_files' ) ) {
		return false;
	}
	return $prevent_access;
}
// Add the filter to prevent admin access for non-admin users.
add_filter( 'woocommerce_prevent_admin_access', 'gigneo_woocommerce_prevent_admin_access' );

/**
 * Filter the media library for logged-in users.
 *
 * This function filters the media library to show only the media uploaded by the current user.
 *
 * @param array $query The query arguments.
 * @return array The modified query arguments.
 * @since 0.0.1
 */
function gigneo_filter_media_library( $query ) {

	if ( ! is_user_logged_in() ) {
		return $query;
	}

	// phpcs:ignore WordPress.Security.NonceVerification -- Safe: only checking flag, not processing sensitive data.
	if ( isset( $_POST['query']['gigneo_author'] ) ) {
		$query['author'] = get_current_user_id();
	}

	return $query;
}
// Add the filter to modify the media library query.
add_filter( 'ajax_query_attachments_args', 'gigneo_filter_media_library' );


/**
 * Filter the comments query clauses to exclude comments of type 'order_activity', 'order_private_note', 'gigneo_ticket', 'gigneo_ticket_note'.
 *
 * @param array $clauses The SQL clauses for the comments query.
 * @param WP_Comment_Query $comment_query The WP_Comment_Query instance.
 *
 * @since 0.0.1
 */
add_filter(
	/**
	 * @param $clauses
	 * @param $comment_query
	 *
	 * @return mixed
	 */    'comments_clauses',
	function ( $clauses, $comment_query ) {
		global $wpdb;

		if ( empty( $comment_query->query_vars['type'] ) ) {
			$clauses['where'] .= $wpdb->prepare(
				" AND {$wpdb->comments}.comment_type NOT IN (%s, %s, %s, %s)",
				'order_activity',
				'order_private_note',
				'gigneo_ticket',
				'gigneo_ticket_note'
			);
		}

		return $clauses;
	},
	10,
	2
);

/**
 * Default fallback for profile info section on overview page.
 *
 * @param array $template_args Template arguments.
 * @param int   $profile_id    Profile ID.
 * @since 0.0.1
 */
if ( ! function_exists( 'gigneo_dashboard_account_overview_side_profile_card_default' ) ) {
	function gigneo_dashboard_account_overview_side_profile_card_default( $template_args, $profile_id ) {
		gigneo_load_template( 'dashboard/account/parts/overview/profile-info', true, $template_args );
	}
}
add_action( 'gigneo_dashboard_account_overview_side_profile_card', 'gigneo_dashboard_account_overview_side_profile_card_default', 10, 2 );
