<?php
if ( ! function_exists( 'wpj_get_settings_tab_number_by_field_id' ) ) {
	function wpj_get_settings_tab_number_by_field_id( $field_id ) {
		return class_exists( 'Redux_Helpers' ) ? Redux_Helpers::tab_from_field( ReduxFrameworkInstances::get_instance( 'jobster_settings' ), $field_id ) : false;
	}
}

if ( ! function_exists( 'wpj_get_plugin_file_by_name' ) ) {
	function wpj_get_plugin_file_by_name( $plugin_name ) {
		// This function is expensive
		// Use it only if there is no other way to get access to __FILE__
		$plugin_file = '';

		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$all_plugins = get_plugins();

		// transform to simple file => name array
		array_walk( $all_plugins, function( &$value, $key ) {
			// lowercase for better match with case typos
			$value = strtolower( $value['Name'] );
		} );

		$plugin_name_lower = strtolower( $plugin_name );

		// order by occurrence possibility to short circuit asap
		$plugin_name_variants = [
			'wpjobster ' . $plugin_name_lower,
			'wpjobster ' . $plugin_name_lower . ' gateway',
			$plugin_name_lower,
			$plugin_name_lower . ' gateway',
		];

		// no array_search. array_flip + isset for performance reasons
		$all_plugins = array_flip( $all_plugins );

		foreach ( $plugin_name_variants as $plugin_name_variant ) {
			if ( isset( $all_plugins[ $plugin_name_variant ] ) ) {
				$plugin_file = WP_PLUGIN_DIR . '/' . $all_plugins[ $plugin_name_variant ];

				break;
			}
		}

		return $plugin_file;
	}
}

if ( ! function_exists( 'wpj_get_gateway_default_fields' ) ) {
	function wpj_get_gateway_default_fields( $args = [] ) {
		$defaults = [
			'gateway_file'         => '',
			'gateway_id'           => '',
			'gateway_name'         => '',
			'item_id'              => false, // the EDD item id
			'gateway_version'      => '',
			'gateway_instructions' => [],
			'license'              => true,
			'enable'               => true,
			'enable_sandbox'       => true,
			'exclude_payment_type' => [],
			'button_name'          => true,
			'public_key'           => false,
			'secret_key'           => false,
			'succes_page_url'      => true,
			'fail_page_url'        => true,
			'new_fields'           => []
		];

		$args = wp_parse_args( $args, $defaults );

		extract( $args );

		$fields = [];

		if ( $gateway_instructions ) {
			$fields[] = [
				'id'    => $gateway_id . '-instructions-section',
				'type'  => 'info',
				'style' => 'custom',
				'color' => '#FFCC33',
				'title' => __( 'Gateway instructions', 'wpjobster' ),
				'desc'  => implode( '<br>', $gateway_instructions )
			];
		}

		$fields[] = [
			'id'       => $gateway_id . '-gateway-enable-settings-section',
			'type'     => 'section',
			'title'    => esc_html__( 'Enable the gateway', 'wpjobster' ),
			'indent'   => true,
		];

		if ( $enable ) {
			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_enable',
				'type'     => 'switch',
				'title'    => __( 'Enable', 'wpjobster' ),
				'subtitle' => __( 'Activate the gateway', 'wpjobster' ),
				'default'  => true,
			];
		}

		if ( $enable_sandbox ) {
			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_enable_sandbox',
				'type'     => 'switch',
				'title'    => __( 'Enable sandbox', 'wpjobster' ),
				'subtitle' => __( 'Enable gateway test mode', 'wpjobster' ),
				'default'  => false,
			];
		}

		foreach ( wpj_get_payment_types( $exclude_payment_type ) as $key => $payment_type ) {

			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_enable_' . $key,
				'type'     => 'switch',
				'title'    => $payment_type['enable_label'],
				'subtitle' => $payment_type['hint_label'],
				'default'  => false,
			];

		}

		if ( $public_key || $secret_key ) {
			$fields[] = [
				'id'       => $gateway_id . '-gateway-keys-settings-section',
				'type'     => 'section',
				'title'    => esc_html__( 'Keys', 'wpjobster' ),
				'indent'   => true,
			];
		}

		if ( $public_key ) {
			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_public_key',
				'type'     => 'text',
				'title'    => __( 'Public key', 'wpjobster' ),
				'default'  => '',
			];
		}

		if ( $secret_key ) {
			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_secret_key',
				'type'     => 'text',
				'title'    => __( 'Secret key', 'wpjobster' ),
				'default'  => '',
			];
		}

		if ( $new_fields ) {
			foreach ( $new_fields as $f_key => $f_value ) {
				$fields[] = [
					'id'           => $f_value['unique_id'],
					'type'         => $f_value['type'],
					'title'        => $f_value['title'],
					'indent'       => isset( $f_value['indent'] )       ? $f_value['indent']       : false,
					'subtitle'     => isset( $f_value['subtitle'] )     ? $f_value['subtitle']     : '',
					'desc'         => isset( $f_value['desc'] )         ? $f_value['desc']         : '',
					'default'      => isset( $f_value['default'] )      ? $f_value['default']      : '',
					'required'     => isset( $f_value['required'] )     ? $f_value['required']     : '',
					'options'      => isset( $f_value['options'] )      ? $f_value['options']      : '',
					'item_name'    => isset( $f_value['item_name'] )    ? $f_value['item_name']    : '',
					'group_values' => isset( $f_value['group_values'] ) ? $f_value['group_values'] : '',
					'fields'       => isset( $f_value['fields'] )       ? $f_value['fields']       : '',
					'full_width'   => isset( $f_value['full_width'] )   ? $f_value['full_width']   : '',
					'content'      => isset( $f_value['content'] )      ? $f_value['content']      : ''
				];
			}
		}

		if ( $button_name || $succes_page_url || $fail_page_url ) {
			$fields[] = [
				'id'       => $gateway_id . '-gateway-payment-settings-section',
				'type'     => 'section',
				'title'    => esc_html__( 'Payment', 'wpjobster' ),
				'indent'   => true,
			];
		}

		if ( $button_name ) {
			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_button_caption',
				'type'     => 'text',
				'title'    => __( 'Payment button name', 'wpjobster' ),
				'subtitle' => __( 'Put the gateway button caption you want user to see on purchase page', 'wpjobster' ),
				'default'  => $gateway_name,
			];
		}

		if ( $succes_page_url ) {
			$fields[] = [
				'id'      => 'wpjobster_' . $gateway_id . '_success_page',
				'type'    => 'select',
				'data'    => 'pages',
				'title'   => __( 'Transaction success page', 'wpjobster' ),
				'default' => ! empty( wpj_get_page_by_title( 'Order' ) ) ? wpj_get_page_by_title( 'Order' )->ID : wpj_get_option( 'wpjobster_order_page_id' )
			];
		}

		if ( $fail_page_url ) {
			$fields[] = [
				'id'      => 'wpjobster_' . $gateway_id . '_failure_page',
				'type'    => 'select',
				'data'    => 'pages',
				'title'   => __( 'Transaction failure page', 'wpjobster' ),
				'default' => ! empty( wpj_get_page_by_title( 'Order' ) ) ? wpj_get_page_by_title( 'Order' )->ID : wpj_get_option( 'wpjobster_order_page_id' )
			];
		}

		if ( $license ) {

			if ( $gateway_file === '' ) {
				$gateway_file = wpj_get_plugin_file_by_name( $gateway_name );
			}

			if ( ! class_exists( 'WPJ_Gateway_License' ) )
				require( get_template_directory() . '/lib/plugin-updater/plugin-updater.php' );

			$license_init = new WPJ_Gateway_License(
				[
					'file'       => $gateway_file,
					'item_name'  => $gateway_name,
					'item_id'    => $item_id,
					'version'    => $gateway_version,
					'author'     => 'WPJobster',
					'api_url'    => 'http://wpjobster.com',
					'short_slug' => $gateway_id,
					'full_slug'  => 'wpjobster_' . $gateway_id,
					'type'       => 'gateway'
				]
			);

			$status  = get_option( 'wpjobster_' . $gateway_id . '_license_status' );
			$details = get_option( 'wpjobster_' . $gateway_id . '_license_status_details' );

			ob_start( ); do_action( 'wpjobster_display_' . $gateway_id . '_license_action_button' );
			$plugin_license_action = ob_get_contents(); ob_end_clean();

			$fields[] = [
				'id'       => $gateway_id . '-gateway-license-settings-section',
				'type'     => 'section',
				'title'    => esc_html__( 'License', 'wpjobster' ),
				'indent'   => true,
			];

			$fields[] = [
				'id'       => 'wpjobster_' . $gateway_id . '_license_key',
				'type'     => 'text',
				'title'    => __( 'License', 'wpjobster' ),
				'subtitle' => $status !== false && $status == 'valid' ? sprintf( __( 'Active. %s', 'wpjobster' ), $details ) : __( 'Inactive', 'wpjobster' )
			];

			$fields[] = [
				'id'         => 'wpjobster_' . $gateway_id . '_license_key_action',
				'type'       => 'raw',
				'title'      => __( 'Activate or Deactivate license key', 'wpjobster' ),
				'subtitle'   => __( 'Save the license before pressing the activation button', 'wpjobster' ),
				'full_width' => false,
				'content'    => $plugin_license_action,
				'required'   => array( 'wpjobster_' . $gateway_id . '_license_key', '!=', '' )
			];
		}

		return $fields;
	}
}

if ( ! function_exists( 'wpj_get_license_fields' ) ) {
	function wpj_get_license_fields( $args = [] ) {
		$defaults = [
			'plugin_file'    => '',
			'plugin_id'      => '',
			'plugin_name'    => '',
			'item_id'        => false, // the EDD item id
			'plugin_version' => ''
		];

		$args = wp_parse_args( $args, $defaults );

		extract( $args );

		$fields = [];

		if ( $plugin_file === '' ) {
			$plugin_file = wpj_get_plugin_file_by_name( $plugin_name );
		}

		if ( ! class_exists( 'WPJ_Plugin_License' ) ) {
			require( get_template_directory() . '/lib/plugin-updater/plugin-updater.php' );
		}

		$license_init = new WPJ_Plugin_License(
			[
				'file'       => $plugin_file,
				'item_name'  => $plugin_name,
				'item_id'    => $item_id,
				'version'    => $plugin_version,
				'author'     => 'WPJobster',
				'api_url'    => 'http://wpjobster.com',
				'short_slug' => $plugin_id,
				'full_slug'  => 'wpjobster_' . str_replace( '-', '_', $plugin_id ),
				'textdomain' => 'wpjobster-' . $plugin_id
			]
		);

		$status  = get_option( 'wpjobster_' . $plugin_id . '_license_status' );
		$details = get_option( 'wpjobster_' . $plugin_id . '_license_status_details' );

		ob_start( ); do_action( 'wpjobster_display_' . $plugin_id . '_license_action_button' );
		$plugin_license_action = ob_get_contents(); ob_end_clean();

		$fields[] = [
			'id'       => $plugin_id . '-plugin-license-settings-section',
			'type'     => 'section',
			'title'    => esc_html__( 'License', 'wpjobster' ),
			'indent'   => true,
		];

		$fields[] = [
			'id'       => 'wpjobster_' . $plugin_id . '_license_key',
			'type'     => 'text',
			'title'    => __( 'License', 'wpjobster' ),
			'subtitle' => $status !== false && $status == 'valid' ? sprintf( __( 'Active. %s', 'wpjobster' ), $details ) : __( 'Inactive', 'wpjobster' )
		];

		$fields[] = [
			'id'         => 'wpjobster_' . $plugin_id . '_license_key_action',
			'type'       => 'raw',
			'title'      => __( 'Activate or Deactivate license key', 'wpjobster' ),
			'subtitle'   => __( 'Save the license before pressing the activation button', 'wpjobster' ),
			'full_width' => false,
			'content'    => $plugin_license_action,
			'required'   => array( 'wpjobster_' . $plugin_id . '_license_key', '!=', '' )
		];

		return $fields;
	}
}

if ( ! function_exists( 'wpj_insert_widget' ) ) {
	function wpj_insert_widget( $widget_id, $widget_data, $sidebar ) {
		// Retrieve sidebars, widgets and their instances
		$sidebars_widgets = get_option( 'sidebars_widgets', [] );
		$widget_instances = get_option( 'widget_' . $widget_id, [] );

		// Retrieve the key of the next widget instance
		$numeric_keys = array_filter( array_keys( $widget_instances ), 'is_int' );
		$next_key     = $numeric_keys ? max( $numeric_keys ) + 1 : 2;

		// Add this widget to the sidebar
		if ( ! isset( $sidebars_widgets[ $sidebar ] ) ) {
			$sidebars_widgets[ $sidebar ] = [];
		}

		$sidebars_widgets[ $sidebar ][] = $widget_id . '-' . $next_key;

		// Add the new widget instance
		$widget_instances[ $next_key ] = $widget_data;

		// Store updated sidebars, widgets and their instances
		update_option( 'sidebars_widgets', $sidebars_widgets );
		update_option( 'widget_' . $widget_id, $widget_instances );
	}
}

if ( ! function_exists( 'wpj_show_pagination_bar' ) ) {
	function wpj_show_pagination_bar( $r = [], $page_info = [] ) { ?>

		<div class="pagination-bar">

			<?php
			$tab = ! empty( $page_info['at'] ) ? $page_info['at'] : 'tabs1';
			$pg  = ! empty( $page_info['pg'] ) ? $page_info['pg'] : 'pj';

			echo paginate_links(
				[
					'base'      => add_query_arg(
						array(
							$pg          => '%#%',
							'active_tab' => $tab,
							'status'     => WPJ_Form::get( 'status', '' )
						)
					),
					'prev_next' => false,
					'format'    => '',
					'prev_text' => __( '&laquo;' ),
					'next_text' => __( '&raquo;' ),
					'total'     => $r['lastpage'],
					'current'   => $r['pageno']
				]
			); ?>

		</div>

	<?php }
}

if ( ! function_exists( 'wpj_send_subscription_price_updated_email' ) ) {
	function wpj_send_subscription_price_updated_email( $period = '', $level = '', $price = '' ) {
		$price  = WPJ_Form::post( 'price', $price );
		$period = WPJ_Form::post( 'period', $period );
		$level  = WPJ_Form::post( 'level', $level );

		$subscriptions_results = wpj_get_subscriptions_by_level_and_period( $level, $period );

		if ( $subscriptions_results ) {
			foreach ( $subscriptions_results as $subscription ) {
				wpj_notify_user_translated( 'price_update_subscription', $subscription->user_id, [
					'##subscription_url##' => wpj_get_subscription_link(),
					'##amount_updated##'   => $price
				], '', 'email' );
			}
		}


		if ( wpj_is_ajax_call() ) wp_die();
	}
}