<?php
/**
 * NHT Trading Academy GetLinked Support Plugin
 *
 * @package NHT_Trading_Academy_GetLinked_Support_Plugin
 * @author New Horizon Technology Ltd.
 * @copyright 2024 New Horizon Technology Ltd.
 * @license All rights reserved.
 */

defined( 'ABSPATH' ) or die( 'Access Denied' );

/**
 * Displays admin page for the plugin
 */
function nht_trading_academy_get_linked_support_plugin_admin_display_page() {
	$plugin_url = plugins_url( '/', __DIR__ );
	echo sprintf(
		'<script type="text/javascript">var nhtTradingAcademyGetLinkedSupportPluginAdminPage = %s;</script>',
		json_encode(
			array(
				'pluginBase'          => $plugin_url,
				'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
				'dashboardUrl'        => admin_url( 'index.php' ),
				'nonces'              => array(
					'nht_trading_academy_ping' => wp_create_nonce( 'nht_trading_academy_ping' ),
					'nht_trading_academy_get_configuration_options' => wp_create_nonce( 'nht_trading_academy_get_configuration_options' ),
					'nht_trading_academy_set_configuration_options' => wp_create_nonce( 'nht_trading_academy_set_configuration_options' ),
					'nht_trading_academy_get_redirectable_types' => wp_create_nonce( 'nht_trading_academy_get_redirectable_types' ),
					'nht_trading_academy_set_redirectable_types' => wp_create_nonce( 'nht_trading_academy_set_redirectable_types' ),
					'nht_trading_academy_get_redirectable_posts' => wp_create_nonce( 'nht_trading_academy_get_redirectable_posts' ),
					'nht_trading_academy_get_selectable_products' => wp_create_nonce( 'nht_trading_academy_get_selectable_products' ),
					'nht_trading_academy_flush_rewrite_rules' => wp_create_nonce( 'nht_trading_academy_flush_rewrite_rules' ),
				),
				'hasWooCommerce'      => function_exists( 'WC' ) ? true : false,
				'hasPrettyPermalinks' => get_option( 'permalink_structure' ) !== '',
				'postbacks'           => array(
					'registration' => array(
						'url'  => get_rest_url( null, '/nht-trading-academy-get-linked-support/v1/postback/registration' ),
						'args' => array( 'email', 'firstName', 'lastName', 'password', 'advertiserhash' ),
					),
				),
			)
		)
	);
	echo '<div id="nht-trading-academy-get-linked-support-plugin-admin-page"></div>';
}

/**
 * Adds admin page for the plugin
 */
function nht_trading_academy_get_linked_support_plugin_admin_add_page() {
	add_submenu_page(
		'options-general.php',
		'NHT Trading Academy GetLinked Support Plugin',
		'GetLinked Support',
		'activate_plugins',
		'nht-trading-academy-get-linked-support-plugin',
		'nht_trading_academy_get_linked_support_plugin_admin_display_page'
	);
}

add_action( 'admin_menu', 'nht_trading_academy_get_linked_support_plugin_admin_add_page' );

/**
 * Enqueue admin styles and scripts
 */
function nht_trading_academy_enqueue_admin_styles_and_scripts() {
	$plugin_url = plugins_url( '/', __DIR__ );
	wp_enqueue_style(
		'nht-trading-academy-get-linked-support-plugin-admin',
		$plugin_url . 'assets/nht-trading-academy-get-linked-support-plugin-admin.css',
		array(),
		'0.1.0'
	);
	wp_enqueue_script(
		'nht-trading-academy-get-linked-support-plugin-admin',
		$plugin_url . 'assets/nht-trading-academy-get-linked-support-plugin-admin.js',
		array( 'wp-ajax-response' ),
		'0.1.0',
		true
	);
}

add_action( 'admin_enqueue_scripts', 'nht_trading_academy_enqueue_admin_styles_and_scripts' );

/**
 * Handles AJAX request to ping the server
 * Usage: ajax('nht_trading_academy_ping')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_ping() {
	wp_send_json_success( 'Pong' );
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_ping', 'nht_trading_academy_wp_ajax_nht_trading_academy_ping' );

/**
 * Handles AJAX request for the current configuration options
 * Usage: ajax('nht_trading_academy_get_configuration_options')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_get_configuration_options() {
	$options = get_options(
		array(
			'nht_trading_academy_redirectable_post_types',
			'nht_trading_academy_default_redirection_post',
			'nht_trading_academy_default_products',
			'nht_trading_academy_advertiser_hashes',
		)
	);
	if ( ! is_array( $options['nht_trading_academy_redirectable_post_types'] ) ) {
		$options['nht_trading_academy_redirectable_post_types'] = array( 'post', 'page' );
	}
	if ( false === $options['nht_trading_academy_default_redirection_post'] ) {
		$options['nht_trading_academy_default_redirection_post'] = '';
	} else {
		$options['nht_trading_academy_default_redirection_post'] = (int) $options['nht_trading_academy_default_redirection_post'];
	}
	if ( ! is_array( $options['nht_trading_academy_default_products'] ) ) {
		$options['nht_trading_academy_default_products'] = array();
	} else {
		$options['nht_trading_academy_default_products'] = array_map( 'intval', $options['nht_trading_academy_default_products'] );
	}
	if ( ! is_array( $options['nht_trading_academy_advertiser_hashes'] ) ) {
		$options['nht_trading_academy_advertiser_hashes'] = array();
	}
	wp_send_json_success( $options );
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_get_configuration_options', 'nht_trading_academy_wp_ajax_nht_trading_academy_get_configuration_options' );

/**
 * Handles AJAX request for the current configuration options
 * Usage: ajax('nht_trading_academy_set_configuration_options')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_set_configuration_options() {
	if ( is_array( $_POST['redirectable_post_types'] ) ) {
		update_option( 'nht_trading_academy_redirectable_post_types', $_POST['redirectable_post_types'] );
	} else {
		update_option( 'nht_trading_academy_redirectable_post_types', array() );
	}
	if ( is_numeric( $_POST['default_redirection_post'] ) ) {
		update_option( 'nht_trading_academy_default_redirection_post', $_POST['default_redirection_post'] );
	}
	if ( is_array( $_POST['default_products'] ) ) {
		update_option( 'nht_trading_academy_default_products', $_POST['default_products'] );
	} else {
		update_option( 'nht_trading_academy_default_products', array() );
	}
	if ( is_array( $_POST['advertiser_hashes'] ) ) {
		update_option( 'nht_trading_academy_advertiser_hashes', $_POST['advertiser_hashes'] );
	} else {
		update_option( 'nht_trading_academy_advertiser_hashes', array() );
	}
	wp_send_json_success();
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_set_configuration_options', 'nht_trading_academy_wp_ajax_nht_trading_academy_set_configuration_options' );

/**
 * Handles AJAX request which returns a list of posts types can be redirected to
 * Usage: ajax('nht_trading_academy_get_redirectable_types')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_get_redirectable_types() {
	// Get all public post types, excluding built-ins like attachments, revisions, etc.
	$post_types = get_post_types(
		array(
			'public'   => true,
			'_builtin' => false,
		),
		'objects'
	);

	// Initialize an array to hold our formatted results.
	$redirectable_types = array();

	// Iterate through the post types to format them as required.
	foreach ( $post_types as $post_type ) {
		$redirectable_types[] = array(
			'value' => $post_type->name,
			'text'  => $post_type->labels->singular_name,
		);
	}

	// Also include standard posts and pages.
	$standard_types = array(
		'post' => 'Post',
		'page' => 'Page',
	);

	foreach ( $standard_types as $type_key => $type_name ) {
		$redirectable_types[] = array(
			'value' => $type_key,
			'text'  => $type_name,
		);
	}

	// Send the JSON response with the formatted post types.
	wp_send_json_success( $redirectable_types );

	// Terminate execution to prevent further output.
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_get_redirectable_types', 'nht_trading_academy_wp_ajax_nht_trading_academy_get_redirectable_types' );

/**
 * Handles AJAX request saves the redirectable post types
 * Usage: ajax('nht_trading_academy_set_redirectable_types')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_set_redirectable_types() {
	// Get all public post types, excluding built-ins like attachments, revisions, etc.
	$post_types = get_post_types(
		array(
			'public'   => true,
			'_builtin' => false,
		),
		'objects'
	);
	if ( is_array( $_POST['redirectable_post_types'] ) ) {
		update_option( 'nht_trading_academy_redirectable_post_types', $_POST['redirectable_post_types'] );
	} else {
		wp_send_json_error( null, 400 );
	}
	// Send the JSON response with the formatted post types.
	wp_send_json_success();

	// Terminate execution to prevent further output.
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_set_redirectable_types', 'nht_trading_academy_wp_ajax_nht_trading_academy_set_redirectable_types' );


/**
 * Handles AJAX request which returns a list of posts which can be redirected to
 * Usage: ajax('nht_trading_academy_get_redirectable_posts')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_get_redirectable_posts() {
	// Load the redirectable post types from the options.
	$redirectable_types = get_option( 'nht_trading_academy_redirectable_post_types' );

	// If the option is not an array, default to post and page.
	if ( ! is_array( $redirectable_types ) ) {
		$redirectable_types = array( 'post', 'page' );
	}

	// Get all posts of the redirectable types.
	$posts = get_posts(
		array(
			'post_type'      => $redirectable_types,
			'posts_per_page' => -1,
		)
	);

	// Initialize an array to hold our formatted results.
	$redirectable_posts = array();

	// If WooCommerce has been activated, get the checkout page ID.
	$checkout_page_id = null;
	if ( function_exists( 'WC' ) ) {
		$checkout_page_id = wc_get_page_id( 'checkout' );
	}

	// Iterate through the posts to format them as required.
	foreach ( $posts as $post ) {
		// Get the name of the post type.
		$post_type = get_post_type_object( $post->post_type );

		// Add the post to the formatted results.
		$redirectable_posts[] = array(
			'value'      => $post->ID,
			'text'       => $post->post_title,
			'typeValue'  => $post->post_type,
			'typeText'   => $post_type->labels->singular_name,
			'permalink'  => get_permalink( $post->ID ),
			'isCheckout' => $checkout_page_id === $post->ID ? true : false,
		);
	}

	// Send the JSON response with the formatted posts.
	wp_send_json_success( $redirectable_posts );
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_get_redirectable_posts', 'nht_trading_academy_wp_ajax_nht_trading_academy_get_redirectable_posts' );

/**
 * Handles AJAX request which returns a list of products which can be automatically added to the cart
 * Usage: ajax('nht_trading_academy_get_selectable_products')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_get_selectable_products() {
	if ( function_exists( 'WC' ) ) {
		$products            = wc_get_products(
			array(
				'status' => 'publish',
			)
		);
		$selectable_products = array();
		foreach ( $products as $product ) {
			$selectable_products[] = array(
				'value' => $product->get_id(),
				'text'  => $product->get_name(),
			);
		}
		wp_send_json_success( $selectable_products );
	} else {
		wp_send_json_success( array() );
	}
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_get_selectable_products', 'nht_trading_academy_wp_ajax_nht_trading_academy_get_selectable_products' );

/**
 * Handles AJAX request to flush the rewrite rules
 * Usage: ajax('nht_trading_academy_flush_rewrite_rules')
 */
function nht_trading_academy_wp_ajax_nht_trading_academy_flush_rewrite_rules() {
	flush_rewrite_rules();
	wp_send_json_success();
	wp_die();
}

add_action( 'wp_ajax_nht_trading_academy_flush_rewrite_rules', 'nht_trading_academy_wp_ajax_nht_trading_academy_flush_rewrite_rules' );


/**
 * Prepend the plugin's admin page to the Plugin Action links
 *
 * @param array $links The existing plugin action links.
 */
function nht_trading_academy_get_linked_support_plugin_admin_action_links( $links ) {
	$links = array_merge(
		array(
			'<a href="' . admin_url( 'admin.php?page=nht-trading-academy-get-linked-support-plugin' ) . '">Settings</a>',
		),
		$links
	);
	return $links;
}

add_filter( 'plugin_action_links_' . plugin_basename( $nht_trading_academy_get_linked_support_plugin_file ), 'nht_trading_academy_get_linked_support_plugin_admin_action_links' );
