<?php

/**
 * Enqueues scripts and styles for the setup pages in the admin area.
 *
 * This function conditionally loads specific JavaScript and CSS files for the plugin's
 * setup pages based on the current admin page hook suffix. It also defines a JavaScript
 * variable (`idf_ajaxurl`) used for AJAX requests within the admin scripts.
 *
 * @since x.x.x
 *
 * @param string $hook_suffix The current page's hook suffix in the admin area.
 */
add_action( 'admin_enqueue_scripts', 'idf_enqueue_admin_main_scripts', 10 );
function idf_enqueue_admin_main_scripts( $hook_suffix ) {
	$idf_page_prefix = 'ignitiondeck_page_';
	$allowed_pages = apply_filters( 'idf_admin_pages', array(
		'toplevel_page_idf',
		$idf_page_prefix . 'idf-install',
		$idf_page_prefix . 'idf-upgrade',
		$idf_page_prefix . 'idf-themes',
		$idf_page_prefix . 'idf-configure',
		$idf_page_prefix . 'idf-connect',
		$idf_page_prefix . 'ignitiondeck',
		$idf_page_prefix . 'deck-builder',
		$idf_page_prefix . 'idc-orders',
		$idf_page_prefix . 'idc-process-pre-authorizations',
		$idf_page_prefix . 'idc-order-data-export',
		$idf_page_prefix . 'idc-commerce',
		$idf_page_prefix . 'idc-gateways',
		$idf_page_prefix . 'idc-backer-dashboard',
		$idf_page_prefix . 'idc-email-templates',
		$idf_page_prefix . 'idc-products',
		$idf_page_prefix . 'idc-product-linking',
		$idf_page_prefix . 'idc-digital-downloads',
		$idf_page_prefix . 'idc-upgrade-pathways',
		$idf_page_prefix . 'idc-troubleshooting',
	) );

	global $idf_current_version;

	if ( in_array( $hook_suffix, $allowed_pages ) ) {
		wp_enqueue_script('popper', plugin_dir_url( __FILE__ ) . 'lib/popper/popper.min.js', array(), '2.11.8', true);

		wp_enqueue_style( 'idf-tippy-css', plugin_dir_url( __FILE__ ) . 'lib/tippy/tippy.css' );
		wp_enqueue_script( 'idf-tippy-js', plugin_dir_url( __FILE__ ) . 'lib/tippy/tippy-bundle.umd.min.js', array('popper'), '6.3.7', true );

		wp_enqueue_style( 'idf-select2-css', plugin_dir_url( __FILE__ ) . 'lib/select2/select2.min.css' );
		wp_enqueue_script( 'idf-select2-js', plugin_dir_url( __FILE__ ) . 'lib/select2/select2.min.js', array('jquery'), '4.1.0', true );

		wp_enqueue_style( 'idf-admin-main-css', plugin_dir_url( __FILE__ ) . 'css/idf-admin-main.css', array(), $idf_current_version );
		wp_enqueue_script( 'idf-admin-main-js', plugin_dir_url( __FILE__ ) . 'js/idf-admin-main.min.js', array( 'jquery', 'idf-tippy-js', 'idf-select2-js' ), $idf_current_version, true );

		wp_localize_script(
			'idf-admin-main-js',
			'idf_ajax_object',
			array(
				'ajax_url'        => admin_url( 'admin-ajax.php' ),
				'site_url'        => site_url(),
				'ajax_nonce'      => wp_create_nonce( 'ignitiondeck-ajax-nonce' ),
				'idc_cc_gateways' => get_idc_cc_gateways_keys(),
			)
		);

		if ( $idf_page_prefix . 'idc-gateways' === $hook_suffix ) {
			wp_register_style('sc_buttons', plugin_dir_url( __FILE__ ) . '../idcommerce/lib/connect-buttons-min.css' );
			wp_register_script('id_stripe_connect', plugin_dir_url( __FILE__ ) . '../idcommerce/classes/modules/stripecheckout/js/id_stripe_connect.js', array( 'jquery' ), $idf_current_version, true );
			wp_register_script('md_sc', plugin_dir_url( __FILE__ ) . '../idcommerce/js/mdSC-min.js', array( 'jquery' ), $idf_current_version, true );
			wp_enqueue_style('sc_buttons');
			wp_enqueue_script('id_stripe_connect');
			wp_enqueue_script('md_sc');

			wp_register_script('square_admin_js', plugin_dir_url( __FILE__ ) . '../idcommerce/classes/modules/square/js/admin/id_square_admin-min.js');
			wp_enqueue_script('square_admin_js');
		}

		if ( $idf_page_prefix . 'idc-products' === $hook_suffix ) {
			wp_register_script('md_sc', plugin_dir_url( __FILE__ ) . '../idcommerce/js/mdSC-min.js', array( 'jquery' ), $idf_current_version, true );
			wp_enqueue_script('md_sc');
		}

	}

}

add_action('admin_init', 'idf_admin_init');

/**
 * Initialize the IDF admin functionality.
 *
 * This function triggers the 'idf_notice_checks' action hook during admin initialization.
 *
 * @return void
 */
function idf_admin_init() {
	$modules_instance = new ID_Modules();
	$modules_instance->set_module_status( 'helix', 0 );
	do_action('idf_notice_checks');
}

add_action('admin_menu', 'idf_admin_menus', 10);


/**
 * Add admin menus for IgnitionDeck.
 *
 * This function adds admin menus for IgnitionDeck, including the dashboard and various
 * extensions. It also handles the display of notice counts and menu items based on user
 * capabilities and plugin licenses.
 */
function idf_admin_menus() {
	if (current_user_can('manage_options')) {
		global $admin_page_hooks;
		add_menu_page(__('IgnitionDeck', 'idf'), __('IgnitionDeck', 'idf'), 'manage_options', 'idf', 'idf_render_setup_page', 'dashicons-ignitiondeck');
		$admin_page_hooks['idf'] = 'ignitiondeck';
	}
}

add_action( 'admin_menu', 'idf_register_setup_menu_pages', 10 );
/**
 * Registers submenu pages for the plugin.
 *
 * Adds 'Register' and 'Configure' submenu pages to the custom 'idf' menu
 * in the WordPress admin dashboard. These pages are intended for plugin setup and configuration.
 *
 * @since x.x.x
 */
function idf_register_setup_menu_pages() {
	add_submenu_page('idf', __('Install', 'memberdeck'), __('Setup', 'memberdeck'), 'manage_options', 'idf', 'idf_render_setup_page');
	add_submenu_page('idf', __('Install', 'memberdeck'), __('Install', 'memberdeck'), 'manage_options', 'idf-install', 'idf_render_setup_page');
	add_submenu_page('idf', __('Configure', 'memberdeck'), __('Configure', 'memberdeck'), 'manage_options', 'idf-configure', 'idf_render_setup_page');
	add_submenu_page('idf', __('Upgrade', 'memberdeck'), __('Upgrade', 'memberdeck'), 'manage_options', 'idf-upgrade', 'idf_render_setup_page');
	add_submenu_page('idf', __('Themes', 'memberdeck'), __('Themes', 'memberdeck'), 'manage_options', 'idf-themes', 'idf_render_setup_page');
	add_submenu_page('idf', __('Connect', 'memberdeck'), __('Connect', 'memberdeck'), 'manage_options', 'idf-connect', 'idf_render_setup_page');
}

/**
 * Enqueues scripts and styles for the setup pages in the admin area.
 *
 * This function conditionally loads specific JavaScript and CSS files for the plugin's
 * setup pages based on the current admin page hook suffix. It also defines a JavaScript
 * variable (`idf_ajaxurl`) used for AJAX requests within the admin scripts.
 *
 * @since x.x.x
 *
 * @param string $hook_suffix The current page's hook suffix in the admin area.
 */
add_action('admin_enqueue_scripts', 'idf_enqueue_admin_scripts', 20);
function idf_enqueue_admin_scripts($hook_suffix) {
	$idf_page_prefix = 'ignitiondeck_page_';
	$allowed_pages = array(
		'toplevel_page_idf',
		$idf_page_prefix . 'idf-install',
		$idf_page_prefix . 'idf-upgrade',
		$idf_page_prefix . 'idf-themes',
		$idf_page_prefix . 'idf-configure',
		$idf_page_prefix . 'idf-connect'
	);

	if (in_array($hook_suffix, $allowed_pages)) {
		wp_enqueue_style('idf-wizard');
		wp_enqueue_script('idf-wizard');
	}

}

/**
 * Determines the active tab for the setup pages based on the current page.
 *
 * This function checks the current admin page against a list of known setup pages
 * and returns the active tab's slug and its associated template path. If no active
 * tab is determined (e.g., the current page does not match any known setup page),
 * it defaults to the first tab as the active one.
 *
 * @since x.x.x
 *
 * @param string $current_page The slug of the current admin page.
 * @return array An associative array containing 'active_tab' (the slug of the active tab)
 *               and 'template_path' (the file path of the template associated with the active tab).
 */
function idf_get_setup_page_active_tab($current_page) {
	$tabs = array(
		'idf'            => '_idfMenu/install.php',
		'idf-install'    => '_idfMenu/install.php',
		'idf-upgrade'    => '_idfMenu/upgrade.php',
		'idf-themes'     => '_idfMenu/themes.php',
		'idf-configure'  => '_idfMenu/configure.php',
		'idf-connect'    => '_idfMenu/connect.php'
	);

	foreach ($tabs as $page => $template_path) {
		if ($current_page === $page) {
			return array('active_tab' => $page, 'template_path' => $template_path);
		}
	}

	// Default to Install tab if no active tab is found
	return array('active_tab' => 'idf-install', 'template_path' => '_idfMenu/install.php');
}

/**
 * Retrieves the tabs for the setup pages.
 *
 * Defines and returns the navigation tabs for the plugin's setup pages,
 * determining the active tab based on the current page.
 *
 * @since x.x.x
 *
 * @return array Array of tabs with their titles, URLs, and active states.
 */
function idf_get_setup_page_tabs() {
	$current_page = isset($_GET['page']) ? $_GET['page'] : '';
	$active_tab_info = idf_get_setup_page_active_tab($current_page);
	$tabs = array(
		array(
			'title'  => 'Install',
			'url'    => 'admin.php?page=idf',
			'active' => ($active_tab_info['active_tab'] === 'idf-install' || $active_tab_info['active_tab'] === 'idf'),
		),
		array(
			'title'  => 'Configure',
			'url'    => 'admin.php?page=idf-configure',
			'active' => ($active_tab_info['active_tab'] === 'idf-configure'),
		),
		array(
			'title'  => 'Upgrade',
			'url'    => 'admin.php?page=idf-upgrade',
			'active' => ($active_tab_info['active_tab'] === 'idf-upgrade'),
		),
		array(
			'title'  => 'Themes',
			'url'    => 'admin.php?page=idf-themes',
			'active' => ($active_tab_info['active_tab'] === 'idf-themes'),
		),
		array(
			'title'  => 'Connect',
			'url'    => 'admin.php?page=idf-connect',
			'active' => ($active_tab_info['active_tab'] === 'idf-connect'),
		)

	);

	return $tabs;
}

add_action('idf_after_menu_page_tab_content', 'idf_render_setup_page_after_tabs_content');
/**
 * Includes the template for content displayed after setup page tabs.
 *
 * Renders additional content located in a specific template file,
 * to be displayed after the navigation tabs on setup pages.
 *
 * @since x.x.x
 */
function idf_render_setup_page_after_tabs_content() {
	$current_page = isset($_GET['page']) ? $_GET['page'] : '';
	if ( $current_page === 'idf' || $current_page === 'idf-install' || $current_page === 'idf-upgrade' || $current_page === 'idf-themes' || $current_page === 'idf-configure' || $current_page === 'idf-connect' ) {
		include 'templates/admin/_idfMenu/after-tab-content.php';
	}
}

/**
 * Retrieves CSS classes for setup page wrappers.
 *
 * Returns an array of CSS classes for customizing the appearance of the main wrapper
 * and content wrapper on the plugin's setup pages.
 *
 * @since x.x.x
 *
 * @return array Array of CSS classes for page wrappers.
 */
function idf_get_setup_page_classes(){
	$classes = apply_filters('idf_setup_page_classes', array(
		'main_wrapper_classes'    => 'setup-page-wrapper wizard-box',
		'content_wrapper_classes' => 'wizard-tabs wizard-tab-content'
	));

	return $classes;
}

/**
 * Retrieves the default help links for the plugin.
 *
 * Defines and returns an array of help links to be displayed on the plugin's setup pages,
 * including support and documentation links.
 *
 * @since x.x.x
 *
 * @return array Array of default help links.
 */
function idf_get_default_help_links() {
	$help_links = array(
		array(
			'url'   => 'mailto:support@ignitionwp.com',
			'text'  => 'Support',
			'title' => 'IgnitionDeck Support',
		),
		array(
			'url'   => 'https://docs.ignitiondeck.com',
			'text'  => 'Documentation',
			'title' => 'IgnitionDeck Documentation',
		)
	);

	return $help_links;
}

/**
 * Renders the setup page for the plugin.
 *
 * This function dynamically generates the content for the plugin's setup page based on the current admin page.
 * It determines the active tab using the `idf_get_setup_page_active_tab` function and retrieves the necessary
 * information to construct the page, such as help links, tabs, and CSS classes for styling. Finally, it calls
 * the `idf_render_menu_page_body_and_tabs` function to render the page with the specified tabs, help links,
 * and classes.
 *
 * @since x.x.x
 */
function idf_render_setup_page() {
	$current_page    = isset( $_GET['page'] ) ? $_GET['page'] : '';
	$active_tab_info = idf_get_setup_page_active_tab( $current_page );
	$help_links      = idf_get_default_help_links();
	$tabs            = idf_get_setup_page_tabs();
	$classes         = idf_get_setup_page_classes();

	idf_render_menu_page_body_and_tabs( $tabs, $active_tab_info['template_path'], $help_links, $classes );
}

/**
 * Renders the body and tabs for a custom admin menu page.
 *
 * This function dynamically generates the body content and navigation tabs
 * for a custom admin menu page, including help links and optional custom page content.
 *
 * @since x.x.x
 *
 * @param array  $tabs                       Array of tabs for navigation. Each element should be
 *                                           an associative array containing 'title', 'url', and 'active' keys.
 * @param string $page_content_template_path Path to the content template file.
 * @param array  $help_links                 Array of help links. Each link should be an associative array
 *                                           containing 'url', 'text', and 'title'.
 * @param array  $classes                    Array of CSS classes for page wrappers. Should contain
 *                                           'main_wrapper_classes' and 'content_wrapper_classes'.
 * @param string $page_note                  The note of the menu page.
 * @param string $page_title                 The title of the menu page. Defaults to 'IgnitionDeck Crowdfunding'.
 */
function idf_render_menu_page_body_and_tabs( $tabs = array(), $page_content_template_path = '', $help_links = array(), $classes = array(), $page_note = '' ,$page_title = 'IgnitionDeck Crowdfunding' ) {
	include 'templates/admin/menu-page.php';
}

function idf_render_menu_page_section_header( $section_title, $help_links = array() ) {
	include 'templates/admin/section-header.php';
}

function idf_render_settings_modal( $modal_content_template_path = '', $modal_form_submission_key = '' ) {
	include 'templates/admin/modal.php';
}

add_action('wp_ajax_load_feature_settings', 'handle_load_feature_settings');

/**
 * Handles AJAX request to load feature settings.
 *
 * This function dynamically loads the template and form submission key for the requested feature.
 * Paths and form submission keys are filtered to allow customization and modular extensions.
 *
 * @return void
 */
function handle_load_feature_settings() {
	// Verify nonce and user capability.
	if ( ! check_ajax_referer( 'ignitiondeck-ajax-nonce' ) || ! current_user_can( 'administrator' ) ) {
		wp_send_json_error( __( 'Invalid request.', 'ignitiondeck' ) );
	}

	// Get the feature key from the AJAX request.
	$feature_key = isset( $_POST['feature_key'] ) ? sanitize_text_field( wp_unslash( $_POST['feature_key'] ) ) : '';

	// Define default template paths.
	$template_paths = apply_filters(
		'idf_feature_settings_template_paths',
		[
			'recaptcha' => IDF_PATH . '/classes/modules/recaptcha/templates/admin/recaptcha-settings.php',
			'stripe_express_settings' => IDC_PATH . '/templates/admin/stripe-express-settings.php',
		]
	);

	// Define default form submission keys.
	$submission_keys = apply_filters(
		'idf_feature_settings_submission_keys',
		[
			'recaptcha' => 'submit_id_recaptcha_settings',
			'stripe_express_settings' => 'stripe_express_settings_submit',
		]
	);

	// Determine the template path and form submission key.
	$modal_content_template_path = isset( $template_paths[ $feature_key ] ) ? $template_paths[ $feature_key ] : '';
	$modal_form_submission_key   = isset( $submission_keys[ $feature_key ] ) ? $submission_keys[ $feature_key ] : '';

	// If no template path is found, return an error.
	if ( empty( $modal_content_template_path ) ) {
		wp_send_json_error( __( 'Invalid feature key.', 'ignitiondeck' ) );
	}

	// Render the settings modal content.
	ob_start();
	idf_render_settings_modal( $modal_content_template_path, $modal_form_submission_key );
	$content = ob_get_clean();

	// Send the response back to the client.
	wp_send_json_success( [ 'content' => $content ] );
}

/**
 * Hide specific sub-menu pages in the WordPress admin.
 *
 * This function adds custom CSS to the admin head to hide
 * specific sub-menu items in the WordPress dashboard. It targets
 * the 'Helix' and 'IDC reCAPTCHA' pages by their slug in the admin menu.
 *
 * @action admin_head Adds custom CSS to the admin head section.
 */
function hide_ign_sub_menu_pages() {
	?>
	<style>
    /* Targeting specific admin menu items by their page slug and hiding them. */
    li a[href="admin.php?page=helix"],
    li a[href="admin.php?page=idc_recaptcha"],
    li a[href="admin.php?page=idf-install"],
    li a[href="admin.php?page=idf-upgrade"],
    li a[href="admin.php?page=idf-themes"],
    li a[href="admin.php?page=idf-configure"],
    li a[href="admin.php?page=idf-connect"] {
      display: none !important;
    }
	</style>
	<?php
}
add_action('admin_head', 'hide_ign_sub_menu_pages');

/**
 * Displays a content restriction message with an upgrade link.
 *
 * @return void
 */
function idf_content_restriction_message( $type = 'license', $exit = true, $message_part = '' ) {
	if ( ! is_idc_licensed() && $type === 'license' ) {
		echo '<div id="message" class="error">';
		printf(
		/* translators: %1$s: Opening <a> tag, %2$s: Closing </a> tag. */
			'<p>' . esc_html__( 'Please %1$sUpgrade%2$s to a paid license. ' . esc_attr( $message_part ) . '', 'memberdeck' ) . '</p>',
			'<a href="' . esc_url( admin_url( 'admin.php?page=idf-upgrade' ) ) . '">',
			'</a>'
		);
		echo '</div>';
		$exit ? exit : '';
	}
	if ( idf_platform() != 'idc' && $type === 'commerce-platform' ) {
		echo '<div id="message" class="error">';
		printf(
		/* translators: %1$s: Opening <a> tag, %2$s: Closing </a> tag. */
			'<p>' . esc_html__( 'Please select IgnitionDeck Commerce as the e-commerce platform in order to configure ' . esc_attr( $message_part ) . '. %1$sUpgrade%2$s', 'memberdeck' ) . '</p>',
			'<a href="' . esc_url( admin_url( 'admin.php?page=idf-upgrade' ) ) . '">',
			'</a>'
		);
		echo '</div>';
		$exit ? exit : '';
	}
}


add_action('admin_menu', 'idf_dev_menus', 100);

/**
 * Display a notice for out-of-date IgnitionDeck plugins installation.
 *
 * This function checks the installed versions of IgnitionDeck addons and displays
 * a notice if any addon is outdated compared to the main plugin.
 *
 * @return void
 */
function update_ignitiondeck_addons_notice() {
	// Required plugins and versions.
	$main_plugin = 'ignitiondeck/idf.php';
	$addons = [
		'idcommerce/idcommerce.php' => '2.0.0',
		'ignitiondeck-crowdfunding/ignitiondeck.php' => '3.0.0',
		'idfu/idfu.php' => '2.0.0',
		'mixpanel-md/mixpanel-md.php' => '2.0.0',
		'shareasale-md/shareasale-md.php' => '2.0.0',
		'idstretch/idstretch.php' => '2.0.0',
		'idsocial/idsocial.php' => '2.0.0',
	];
	$main_plugin_required_version = '2.0.0';

	// Get all installed plugins.
	$installed_plugins = get_plugins();

	// Check if the main plugin exists and meets the version requirement.
	if (
		isset( $installed_plugins[ $main_plugin ] ) &&
		version_compare( $installed_plugins[ $main_plugin ]['Version'], $main_plugin_required_version, '>=' )
	) {
		$outdated_addons = [];

		// Loop through addons to check versions.
		foreach ( $addons as $slug => $required_version ) {
			if (
				isset( $installed_plugins[ $slug ] ) &&
				version_compare( $installed_plugins[ $slug ]['Version'], $required_version, '<' )
			) {
				$outdated_addons[] = $installed_plugins[ $slug ]['Name'];
			}
		}

		// If there are outdated addons, display an admin notice.
		if ( ! empty( $outdated_addons ) ) {
			$addons_list = implode( ', ', $outdated_addons );
			?>
      <div class="notice notice-error">
        <p>
					<?php
					echo esc_html(
						sprintf(
						/* translators: %s is a list of outdated plugins. */
							__( 'Action Required! The following IgnitionDeck plugins are outdated and must be upgraded: %s. Older versions have been deprecated.', 'ignitiondeck' ),
							$addons_list
						)
					);
					?>
        </p>
      </div>
			<?php
		}
	}
}
add_action( 'admin_notices', 'update_ignitiondeck_addons_notice' );


/**
 * Add developer tools submenu to IgnitionDeck admin menu.
 *
 * This function adds a developer tools submenu to the IgnitionDeck admin menu
 * if the development mode is enabled. It also enqueues the necessary admin styles.
 */
function idf_dev_menus() {
	if (idf_dev_mode()) {
		$dev_menu = add_submenu_page( 'idf' , __('Dev Tools', 'idf'), apply_filters('idf_menu_title_idf-dev-tools', __('Dev Tools', 'idf')), 'manage_options', 'idf-dev-tools', 'idf_dev_tools');
		add_action('admin_print_styles-'.$dev_menu, 'idf_admin_enqueues');
		//add_action('admin_print_styles-'.$dev_menu, 'idf_dev_tools_enqueues');
	}
}

/**
 * Display the developer tools.
 *
 * This function captures the output of phpinfo, removes the surrounding HTML, and
 * includes the template to display the developer tools.
 */
function idf_dev_tools() {
	ob_start();
	phpinfo();
	$php_info = ob_get_contents();
	ob_end_clean();
	$php_info = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $php_info);
	include_once 'templates/admin/_devTools.php';
}

add_action('idf_notice_checks', 'idf_notice_checks');

/**
 * Check for IgnitionDeck Commerce version and display notice if out of date.
 *
 * This function checks the version of IgnitionDeck Commerce and displays a notice
 * if it is out of date. It retrieves the current and new versions, compares them,
 * and adds an admin notice if the current version is older than the new version.
 */
function idf_notice_checks() {
	// IDC version check
	if (idf_has_idc()) {
		$idc_data = get_plugin_data(WP_PLUGIN_DIR . '/idcommerce/idcommerce.php');
		if (!empty($idc_data['Version'])) {
			$current_idc_version = $idc_data['Version'];
			$versions = get_transient('idf_plugin_versions');
			if (isset($versions['idcommerce/idcommerce.php'])) {
				$new_idc_version = $versions['idcommerce/idcommerce.php'];
				if (version_compare($current_idc_version, $new_idc_version, '<')) {
					add_action('admin_notices', 'idf_idc_notice');
				}
			}
		}
	}
}

/**
 * Display a notice for an out-of-date IgnitionDeck Commerce installation.
 *
 * This function displays a notice for an out-of-date IgnitionDeck Commerce installation.
 * It outputs an admin notice with a message and a link to update to the latest version.
 */
function idf_idc_notice() {
	echo '<div class="updated">
            <p>' . 
                esc_html__('Your IgnitionDeck Commerce installation is out of date.', 'ignitiondeck') . ' <a href="' . esc_url(admin_url('update-core.php')) . '">' . esc_html__('Click here', 'ignitiondeck') . '</a> ' . esc_html__('to update to the latest version.', 'ignitiondeck') . 
            '</p>
        </div>';
}


add_action('admin_enqueue_scripts', 'idf_prepare_admin_scripts');

/**
 * Prepare admin scripts for IgnitionDeck.
 *
 * This function registers the necessary scripts and styles for the IgnitionDeck
 * admin area, including the main admin script, wizard script, admin media script,
 * magnific script, admin styles, wizard styles, and magnific styles.
 */
function idf_prepare_admin_scripts() {
	global $idf_current_version;

	wp_register_script('idf-admin', plugins_url('/js/idf-admin-min.js', __FILE__), array(), $idf_current_version, true);
	wp_register_style('idf-admin', plugins_url('/css/idf-admin-min.css', __FILE__), array(), $idf_current_version, true);
	wp_register_script('idf-wizard', plugins_url('/js/idf-wizard.js', __FILE__), array('wp-i18n'), $idf_current_version, true);
	wp_register_style('idf-wizard', plugins_url('/css/idf-wizard.css', __FILE__), array(), $idf_current_version);
	wp_register_script('magnific', plugins_url('lib/magnific/magnific-min.js', __FILE__), array(), $idf_current_version, true);
	wp_register_style('magnific', plugins_url('lib/magnific/magnific-min.css', __FILE__), array(), $idf_current_version, true);
	wp_register_script('idf-admin-media', plugins_url('/js/idf-admin-media-min.js', __FILE__), array(), $idf_current_version, true);

// Localize the nonce and the AJAX URL.
	wp_localize_script(
		'idf-wizard',
		'idfWizardParams',
		array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ), // WordPress AJAX handler.
		'nonce'   => wp_create_nonce( 'idf_setup_nonce_action' )// Nonce for verification.
		)
	);
	wp_set_script_translations('idf-wizard', 'ignitiondeck');

}

add_action('admin_enqueue_scripts', 'idf_prepare_admin_localization');

/**
 * Prepare admin localization for IgnitionDeck.
 *
 * This function prepares the necessary localization for the IgnitionDeck admin area,
 * including site URL, AJAX URL, platform, launchpad link, and IgnitionDeck version.
 *
 * @return void
 */
function idf_prepare_admin_localization() {
	$platform = idf_platform();
	$prefix = 'http';
	if (is_ssl()) {
		$prefix = 'https';
	}
	if (function_exists('get_plugin_data')) {
		$idf_data = get_plugin_data(DIRNAME(__FILE__).'/idf.php');
	}

	wp_add_inline_script( 'idf-admin', 'var idf_admin_siteurl = "'. site_url() . '";' );
	wp_add_inline_script( 'idf-admin', 'var idf_admin_ajaxurl = "'. site_url('/wp-admin/admin-ajax.php') . '";' );
	wp_add_inline_script( 'idf-admin', 'var idf_platform = "'. $platform . '";' );
	wp_add_inline_script( 'idf-admin', 'var launchpad_link = "'. $prefix.'://ignitiondeck.com/id/id-launchpad-checkout/' . '";' );
	wp_add_inline_script( 'idf-admin', 'var idf_version = "'. (isset($idf_data['Version']) ? $idf_data['Version'] : '0.0.0') . '";' );
}

add_action('admin_enqueue_scripts', 'idf_additional_enqueues');

/**
 * Enqueue additional scripts and styles for IgnitionDeck admin area.
 *
 * This function enqueues additional scripts and styles for the IgnitionDeck
 * admin area, including the ignitiondeck-font style, conditional loading of
 * selective css/scripts based on the post type, and admin enqueues if the
 * platform is not legacy.
 */
function idf_additional_enqueues() {
	global $post;
	global $idf_current_version;
	
	wp_register_style('ignitiondeck-font', plugins_url('/lib/ignitiondeckfont/ignitiondeckfont-min.css', __FILE__), array(), $idf_current_version);
	wp_enqueue_style('ignitiondeck-font');
	if (isset($post->post_type) && $post->post_type == 'ignition_product') {
		// load selective css/scripts
		$platform = idf_platform();
		if (empty($platform) || $platform !== 'legacy') {
			idf_admin_enqueues();
		}
	}
}

/**
 * Enqueue admin scripts and styles for IgnitionDeck.
 *
 * This function enqueues admin scripts and styles for the IgnitionDeck admin
 * area, including jquery, dashboard script, media, magnific, admin, wizard,
 * admin media, and conditional loading of dashboard and magnific styles.
 */
function idf_admin_enqueues() {
	wp_enqueue_script('jquery');
	if (menu_page_url('idf', false) == idf_current_url()) {
		wp_enqueue_script('dashboard');
	}
	wp_enqueue_media();
	wp_enqueue_script('magnific');
	wp_enqueue_script('idf-admin');
	wp_enqueue_script('idf-wizard');
	wp_enqueue_script('idf-admin-media');
	if (menu_page_url('idf', false) == idf_current_url()) {
		wp_enqueue_style('dashboard');
	}
	wp_enqueue_style('magnific');
	wp_enqueue_style('idf-admin');
	wp_enqueue_style('idf-wizard');
}

add_action('admin_init', 'filter_idcf_admin');

/**
 * Filter admin actions for IgnitionDeck Crowdfunding.
 *
 * This function filters admin actions for IgnitionDeck Crowdfunding based on the
 * platform. It removes the action 'add_meta_boxes' for 'add_ty_url' if the
 * platform is not empty and not 'legacy'. If the platform is 'wc', it adds the
 * action 'idcf_below_project_settings' for 'idf_wc_settings' and removes the
 * action 'add_meta_boxes' for 'add_purchase_url'.
 */
function filter_idcf_admin() {
	$platform = idf_platform();
	if (!empty($platform) && $platform !== 'legacy') {
		remove_action('add_meta_boxes', 'add_ty_url');
	}
	if ($platform == 'wc') {
		add_action('idcf_below_project_settings', 'idf_wc_settings');
		remove_action('add_meta_boxes', 'add_purchase_url');
	}
}

add_action('plugins_loaded', 'filter_idc_admin');

/**
 * Filter admin actions for IgnitionDeck Commerce.
 *
 * This function filters admin actions for IgnitionDeck Commerce based on the
 * platform. It removes the action 'add_meta_boxes' for 'mdid_project_metaboxes' if the
 * platform is not 'idc'.
 */
function filter_idc_admin() {
	$platform = idf_platform();
	if ($platform !== 'idc') {
		remove_action('add_meta_boxes', 'mdid_project_metaboxes');
	}
}

/**
 * Set and display IgnitionDeck WooCommerce settings.
 *
 * This function sets and displays the IgnitionDeck WooCommerce settings. It retrieves
 * the checkout URL option, updates it if a new value is posted, and includes the
 * WooCommerce settings template.
 *
 * @return void
 */
function idf_wc_settings() {
	if (isset($_GET['wp_id_nonce'])) {
		check_admin_referer('wp_id_nonce', 'wp_id_nonce');
	}

    // Check user capabilities.
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( 'You don\'t have sufficient permissions to manage options.' );
    }
	
	// #devnote create a function for this
	$idf_wc_checkout_url = get_option('idf_wc_checkout_url', 'get_cart_url');
	if (isset($_POST['idf_wc_checkout_url'])) {
		$idf_wc_checkout_url = sanitize_text_field($_POST['idf_wc_checkout_url']);
		update_option('idf_wc_checkout_url', $idf_wc_checkout_url);
	}
	include_once('templates/admin/_wcSettings.php');
}

function get_idc_cc_gateways_keys(){
	$idc_cc_gateways_keys = array(
		'enable_stripe',
		'enable_stripe_checkout',
		'enable_stripe_express',
		'enable_authorize',
		'enable_first_data',
		'enable_square',
		'enable_secupay',
		'enable_paytm',
	);
	return apply_filters( 'idc_cc_gateways_keys', $idc_cc_gateways_keys);
}
