<?php
/**
 * Enquir3 feedback settings.
 */

register_activation_hook( __FILE__, 'eq3f_set_default_options' );

/**
 * Set default options.
 */
function eq3f_set_default_options() {
	eq3f_get_options();
}

/**
 * Get feedback options
 *
 * @return type
 */
function eq3f_get_options() {
	$options = get_option( 'enquir3_feedback_options', array() );

	$new_options['client_key']                          = '';
	$new_options['client_id']                           = '';
	$new_options['remote_url']                          = '';
	$new_options['parent_type']                         = 0;
	$new_options['parent_id']                           = 0;
	$new_options['listing_id']                          = '';
	$new_options['service_taxonomy']                    = '';
	$new_options['staff_taxonomy']                      = '';
	$new_options['additional_taxonomy']                 = array();
	$new_options['feedback_add_text']                   = 'Leave Feedback';
	$new_options['display_additional_questions']        = '';
	$new_options['feedback_email_notification_from']    = get_option( 'admin_email' );
	$new_options['feedback_email_notification_to']      = '';
	$new_options['feedback_email_notification_subject'] = 'New Feedback';
	$new_options['listing_link']                        = '';
	$new_options['display_stood_out_length']            = 150;
	$new_options['display_company_comment_length']      = 100;
	$new_options['auto_publish']                        = '';
	$new_options['thankyou_page_id']                    = 99999;
	$new_options['reply_label']                         = 'Reply';

	$merged_options = wp_parse_args( $options, $new_options );

	$compare_options = array_diff_key( $new_options, $options );
	if ( empty( $options ) || ! empty( $compare_options ) ) {
		update_option( 'enquir3_feedback_options', $merged_options );
	}

	return $merged_options;
}

// Register action hook function to be called when the admin pages are
// starting to be prepared for display.
add_action( 'admin_init', 'eq3f_admin_init' );

/**
 * Function to register the Settings for this plugin
 * and declare the fields to be displayed.
 */
function eq3f_admin_init() {
	// Register our setting group with a validation function
	// so that $_POST handling is done automatically for us.
	register_setting(
		'remsto_feedback_settings',
		'enquir3_feedback_options',
		'eq3f_validate_options'
	);

	// Add a new settings section for client settings.
	add_settings_section(
		'remsto_feedback_client_section',
		'Client Settings',
		'eq3f_client_client_setting_section_callback',
		'remsto_feedback_settings_section'
	);

	// Add a new settings section for feedback settings.
	add_settings_section(
		'remsto_feedback_main_section',
		'Feedback Settings',
		'eq3f_main_setting_section_callback',
		'remsto_feedback_settings_section'
	);

	// Add a new settings section Link to edit thankyou page.
	add_settings_section(
		'remsto_feedback_links_section',
		'Additional Links',
		'eq3f_thankyou_page_edit_callback',
		'remsto_feedback_settings_section'
	);

		// Add the fields for client settings.
	add_settings_field(
		'client_key',
		'Client Key',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_client_section',
		array(
			'name' => 'client_key',
			'size' => 50,
		)
	);

	add_settings_field(
		'client_id',
		'Client ID',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_client_section',
		array(
			'name' => 'client_id',
			'size' => 10,
		)
	);

	add_settings_field(
		'remote_url',
		'Remote URL',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_client_section',
		array(
			'name' => 'remote_url',
			'size' => 50,
		)
	);

	add_settings_field(
		'listing_id',
		'Listing ID',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_client_section',
		array(
			'name' => 'listing_id',
			'size' => 10,
		)
	);

	$feedback_options = get_option( 'enquir3_feedback_options', array() );
	$taxonomy_options = array();
	if ( '' !== $feedback_options['remote_url'] ) {
		try {
			$rc         = new RemstoFeedbackClient( $feedback_options );
			$taxonomies = $rc->listVocabularies();
			foreach ( $taxonomies as $taxonomy ) {
				$taxonomy_options[ $taxonomy->tid ] = $taxonomy->title;
			}
		} catch ( Exception $exc ) {
			echo esc_attr( $exc->getTraceAsString() );
		}
	}

	$staff_taxonomy_options      = $taxonomy_options;
	$staff_taxonomy_options['0'] = 'Free form text';

	add_settings_field(
		'service_taxonomy',
		'Service Taxonomy',
		'eq3f_display_select_list',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name'    => 'service_taxonomy',
			'choices' => $taxonomy_options,
		)
	);

	add_settings_field(
		'staff_taxonomy',
		'Staff Taxonomy',
		'eq3f_display_select_list',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name'    => 'staff_taxonomy',
			'choices' => $staff_taxonomy_options,
		)
	);

	add_settings_field(
		'display_additional_questions',
		'Display Additional Questions?',
		'eq3f_display_check_box',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array( 'name' => 'display_additional_questions' )
	);

	add_settings_field(
		'auto_publish',
		'Auto Publish?',
		'eq3f_display_check_box',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array( 'name' => 'auto_publish' )
	);

	add_settings_field(
		'additional_taxonomy',
		'Additional Taxonomy',
		'eq3f_display_check_box_group',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name'    => 'additional_taxonomy',
			'choices' => $taxonomy_options,
		)
	);

	add_settings_field(
		'feedback_add_text',
		'Add Button Text',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'feedback_add_text',
			'size' => 60,
		)
	);

	add_settings_field(
		'feedback_email_notification_from',
		'From email address',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'feedback_email_notification_from',
			'size' => 150,
		)
	);

	add_settings_field(
		'feedback_email_notification_to',
		'Send email to....',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'feedback_email_notification_to',
			'size' => 150,
		)
	);

	add_settings_field(
		'feedback_email_notification_subject',
		'Mail Subject',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'feedback_email_notification_subject',
			'size' => 150,
		)
	);

	add_settings_field(
		'listing_link',
		'Link to Listing Site',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'listing_link',
			'size' => 150,
		)
	);

	add_settings_field(
		'display_stood_out_length',
		'Limit Feedback comment to char',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'display_stood_out_length',
			'size' => 5,
		)
	);

	add_settings_field(
		'display_company_comment_length',
		'Limit feedback company reply to char',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'display_company_comment_length',
			'size' => 5,
		)
	);

	add_settings_field(
		'reply_label',
		'Label for reply comment',
		'eq3f_display_text_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'reply_label',
			'size' => 150,
		)
	);
	add_settings_field(
		'thankyou_page_id',
		'Thank You Page ID',
		'eq3f_display_hidden_field',
		'remsto_feedback_settings_section',
		'remsto_feedback_main_section',
		array(
			'name' => 'thankyou_page_id',
		),
		array(
			'class' => 'no-padding',
		)
	);
}

/**
 * Validation function to be called when data is posted by user
 * No validation done at this time. Straight return of values.
 *
 * @param array $input Feedback settings.
 * @return array Modified input
 */
function eq3f_validate_options( $input ) {

	// Test email addresses okay.
	if ( ! empty( $input['feedback_email_notification_to'] ) ) {
		$address_list = explode( ', ', $input['feedback_email_notification_to'] );
		$regex        = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
		foreach ( $address_list as $address ) {
			if ( ! preg_match( $regex, $address ) ) {
				add_settings_error(
					'remsto_feedback',
					esc_attr( 'settings_updated' ),
					'Email list error: ' . $input['feedback_email_notification_to'],
					'error'
				);
				$input['feedback_email_notification_to'] = '';
			}
		}
	}

	if ( ! is_numeric( $input['display_stood_out_length'] ) ) {
		add_settings_error(
			'remsto_feedback',
			esc_attr( 'settings_updated' ),
			'Char limit must be a number: ' . $input['display_stood_out_length'],
			'error'
		);
		$input['display_stood_out_length'] = 150;
	}

	if ( ! is_numeric( $input['display_company_comment_length'] ) ) {
		add_settings_error(
			'remsto_feedback',
			esc_attr( 'settings_updated' ),
			'Char limit must be a number: ' . $input['display_company_comment_length'],
			'error'
		);
		$input['display_company_comment_length'] = 100;
	}

	$eq3f_options = get_option( 'enquir3_feedback_options' );
	if($eq3f_options['listing_id'] !== $input['listing_id']) {
		$feedback_client = new RemstoFeedbackClient( $input );
		$feedback_client->linkSiteToParent(
			1,
			$input['listing_id'],
			1,
			$eq3f_options['listing_id'], $input['client_id']);

	}
	return $input;
}

/**
 * Display main settings title.
 */
function eq3f_main_setting_section_callback() {
	// Use a print with p tags to get this to do something.
}

/**
 * Display client settings title.
 */
function eq3f_client_client_setting_section_callback() {
	// Use a print with p tags to get this to do something.
}

/**
 * Display link to edit thank you page.
 */
function eq3f_thankyou_page_edit_callback() {
	$options          = get_option( 'enquir3_feedback_options', array() );
	$thankyou_page_id = $options['thankyou_page_id'];
	$href             = admin_url( "post.php?post=$thankyou_page_id&action=edit" );
	print "<a href='" . esc_html( $href ) . "'>Edit Thank you Page</a>";
}

/**
 * Function to render a text input field.
 *
 * @param array $data Representation of a field.
 */
function eq3f_display_text_field( $data = array() ) {
	if ( isset( $data['size'] ) ) {
		$size_attr = ' size="' . $data['size'] . '" ';
	} else {
		$size_attr = '';
	}
	$options = eq3f_get_options();
	?>
	<input type="text" <?php echo esc_attr( $size_attr ); ?> name="enquir3_feedback_options[<?php echo esc_attr( $data['name'] ); ?>]" value="<?php echo esc_html( $options[ $data['name'] ] ); ?>"/><br />

	<?php
}

/**
 * Function to render a hidden input field.
 *
 * @param array $data Representation of a field.
 */
function eq3f_display_hidden_field( $data = array() ) {
	$options = eq3f_get_options();
	?>
	<input id="eq3f-hidden-field-<?php echo esc_attr( $data['name'] ); ?>" type="hidden" name="enquir3_feedback_options[<?php echo esc_attr( $data['name'] ); ?>]" value="<?php echo esc_html( $options[ $data['name'] ] ); ?>"/><br />
	<script type="text/javascript">jQuery("#eq3f-hidden-field-<?php echo esc_attr( $data['name'] ); ?>").parents('tr').hide();</script> 
	<?php
}

/**
 * Function to render a checkbox.
 *
 * @param array $data Representation of a field.
 */
function eq3f_display_check_box( $data = array() ) {
	$options = eq3f_get_options();
	?>
	<input type="checkbox" name="enquir3_feedback_options[<?php echo esc_attr( $data['name'] ); ?>]" 
																	<?php
																	if ( $options[ $data['name'] ] ) {
																		echo ' checked="checked" ';}
																	?>
		/>
	<?php
}

/**
 * Function to render a checkbox group.
 *
 * @param array $data Representation of a field.
 */
function eq3f_display_check_box_group( $data = array() ) {
	$options = eq3f_get_options();
	?>
	<?php
	foreach ( $data['choices'] as $value => $item ) {
		// Exclude selected service taxonomy.
		if ( $value === (int) $options['service_taxonomy'] ) {
			continue;
		}
		if ( isset( $options[ $data['name'] ][ $value ] ) ) {
			$checked = 'checked';
		} else {
			$checked = '';
		}
		?>

		<div>
			<input type="checkbox" name="enquir3_feedback_options[<?php echo esc_attr( $data['name'] ); ?>][<?php echo esc_attr( $value ); ?>]" value="<?php echo esc_attr( $value ); ?>" <?php echo esc_attr( $checked ); ?>/>
			<?php echo esc_attr( $item ); ?>
		</div>
	<?php } ?>

	<?php
}


/**
 * Function to render a select list.
 *
 * @param array $data Representation of a field.
 */
function eq3f_display_select_list( $data = array() ) {
	$options = eq3f_get_options();
	?>
	<select name='enquir3_feedback_options[<?php echo esc_attr( $data['name'] ); ?>]'>  
		<?php foreach ( $data['choices'] as $value => $item ) { ?>
			<option value="<?php echo esc_attr( $value ); ?>" <?php selected( intval( $options[ $data['name'] ]) === $value ); ?>><?php echo esc_attr( $item ); ?></option>;
		<?php } ?>
	</select>  
	<?php
}

// Register action hook to be called when the administration menu is
// being constructed.
add_action( 'admin_menu', 'eq3f_settings_menu' );

/**
 * Function called when the admin menu is constructed to add a new menu item
 * to the structure
 */
function eq3f_settings_menu() {
	add_options_page(
		'Enquir3 Feedback',
		'Enquir3 Feedback',
		'manage_options',
		'remsto_feedback_settings',
		'eq3f_config_page'
	);
}

/**
 * Function called to render the contents of the plugin
 * configuration page.
 */
function eq3f_config_page() {
	?>
	<div id="remsto_feedback-general" class="wrap">
		<h2>Enquir3 Feedback Settings</h2>

		<form name="enquir3_feedback_options_form_settings_api" method="post" action="options.php">

			<?php settings_fields( 'remsto_feedback_settings' ); ?>

			<?php do_settings_sections( 'remsto_feedback_settings_section' ); ?> 

			<input type="submit" value="Submit" class="button-primary" />
		</form>
	</div>
	<?php
}
