<?php
/**
 * Create Referrers list
 *
 * @class DateBook_Referrers_List
 * @author Pagick Themes
 * @since 4.4.9
 */
	 

/**
 * Load WordPress Table Class
 */
class DateBook_Referrers_List extends WP_List_Table {

	/**
	 * [REQUIRED] You must declare constructor and give some basic params
	 */
	function __construct() {

		global $status, $page;

		parent::__construct(array(
			'singular' => 'field',
			'plural' => 'fields',
		));
	}


	/**
	 * [REQUIRED] this is a default column renderer
	 *
	 * @param $item - row (key, value array)
	 * @param $column_name - string (key)
	 * @return HTML
	 */
	function column_default($item, $column_name) {
		
		return esc_attr($item[$column_name]);
			
	}


	/**
	 * [OPTIONAL] this is example, how to render column with actions,
	 * when you hover row "Edit | Delete" links showed
	 *
	 * @param $item - row (key, value array)
	 * @return HTML
	 */
	function column_name($item) {

		$menu = Options_Framework_Admin::menu_settings();

		if ( isset( $menu['menu_referrer_slug'] ) ) {
			$menu_referrer_slug = $menu['menu_referrer_slug'];
		}

		// links going to /admin.php?page=[your_plugin_page][&other_params]
		// notice how we used $_REQUEST['page'], so action will be done on current page
		// also notice how we use $this->_args['singular'] so in this example it will
		// be something like &custom_field=2
		$actions = array(
			'delete' => sprintf('<a onclick="return confirm(\' %s \')" href="admin.php?page=%s&action=delete&profile_id=%s">%s</a>', esc_html__('Do you really want to delete it?', 'datebook'), esc_attr($menu_referrer_slug), esc_attr($item['profile_id']), esc_html__('Delete', 'datebook')),
		);

		return sprintf('%s %s',
			esc_attr($item['name']),
			$this->row_actions($actions)
		);
	}


	/**
	 * [OPTIONAL] This method processes bulk actions
	 * it can be outside of class
	 * it can not use wp_redirect coz there is output already
	 * in this example we are processing delete action
	 * message about successful deletion will be shown on page in next part
	 */
	function process_bulk_action() {

		if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete'){

			$profile_id = isset($_REQUEST['profile_id']) ? $_REQUEST['profile_id'] : '';

			if (isset($profile_id) && $profile_id > 0) {

				// Update entire array
				// Get entire array
				if ('delete' === $this->current_action()) {

					delete_post_meta($profile_id, 'referrer');

				}
			}
		}
	}


	/**
	 * [REQUIRED] This method return columns to display in table
	 * you can skip columns that you do not want to show
	 * like content, or description
	 *
	 * @return array
	 */
	function get_columns() {

		$columns = array(
			'name' => esc_html__('Referrer name', 'datebook'),
			'profile_url' => esc_html__('Profile URL', 'datebook'),
			'referrer' => esc_html__('Referrer', 'datebook'),
			'sendtoreferrerurl' => esc_html__('Send a request to this site', 'datebook'),
			'date_referred' => esc_html__('Date (referred)', 'datebook'),
			'date_registered' => esc_html__('Date (registered)', 'datebook')
		);

		return $columns;

	}


	/**
	 * [REQUIRED] This is the most important method
	 *
	 * It will get rows from database and prepare them to be showed in table
	 */
	function prepare_items() {
		
		global $wpdb;

		$per_page = 300; // constant, how much records will be shown per page

		$columns = $this->get_columns();
		$hidden = array();
		$sortable = $this->get_sortable_columns();

		// here we configure table headers, defined in our methods
		$this->_column_headers = array($columns, $hidden, $sortable);

		// [OPTIONAL] process bulk action if any
		$this->process_bulk_action();

		$get_all_referrers = array();

		$datebook_referrers_array = $wpdb->get_col("SELECT `meta_value` FROM `$wpdb->postmeta` WHERE `meta_key` = 'referrer'");

		if (count($datebook_referrers_array) > 0) {

			$empty_array = array('referrercode' => '', 'name' => '', 'detect_url_referer' => '', 'slug' => '', 'referrer' => '', 'sendtoreferrerurl' => '', 'profile_id' => '', 'profile_url' => '', 'date_referred' => '', 'date_registered' => '');

			foreach ($datebook_referrers_array as $key => $meta_value) {

				$meta_value = unserialize($meta_value);

				// Check if referrer found
				if(isset($meta_value)) {
					
					$profile_get_permalink = get_permalink($meta_value['profile_id']);

					$meta_value = array_merge($empty_array, $meta_value);

					$get_all_referrers[] = array('referrercode' => $meta_value['referrercode'], 'name' => $meta_value['name'] . ' (' . $meta_value['referrercode'] . ')', 'slug' => $meta_value['slug'] . ' Detected referer: ' . $meta_value['detect_url_referer'], 'referrer' => $meta_value['slug'], 'sendtoreferrerurl' => $meta_value['sendtoreferrerurl'], 'profile_id' => $meta_value['profile_id'], 'profile_url' => $profile_get_permalink, 'date_referred' => $meta_value['date_referred'], 'date_registered' => $meta_value['date_registered']);

				}
			}
		}


		if(is_array($get_all_referrers) && !empty($get_all_referrers)){

			// will be used in pagination settings
			$total_items = count($get_all_referrers);

			// prepare query params, as usual current page, order by and order direction
			$paged = isset($_REQUEST['paged']) ? ($per_page * max(0, intval($_REQUEST['paged']) - 1)) : 0;

			// Define $items array
			// notice that last argument is ARRAY_A, so we will retrieve array
			$this->items = $get_all_referrers;

			// configure pagination
			$this->set_pagination_args(array(
				'total_items' => $total_items, // total items defined above
				'per_page' => $per_page, // per page constant defined at top of method
				'total_pages' => ceil($total_items / $per_page) // calculate pages count
			));
		}
	}
}


/**
 * Load WordPress Table Class
 */
class DateBook_Referrers_Options extends WP_List_Table {

	/**
	 * [REQUIRED] You must declare constructor and give some basic params
	 */
	function __construct() {

		global $status, $page;

		parent::__construct(array(
			'singular' => 'field',
			'plural' => 'fields',
		));
	}


	/**
	 * [REQUIRED] this is a default column renderer
	 *
	 * @param $item - row (key, value array)
	 * @param $column_name - string (key)
	 * @return HTML
	 */
	function column_default($item, $column_name) {
		
		return esc_attr($item[$column_name]);
			
	}


	/**
	 * [OPTIONAL] this is example, how to render specific column
	 *
	 * method name must be like this: "column_[column_name]"
	 *
	 * @param $item - row (key, value array)
	 * @return HTML
	 */
	function column_profile_id($item) {

		if (isset($item['profile_id']) && $item['profile_id'] == 1) {

			$out = '<span style="color:green">' . esc_html__('Yes', 'datebook') . '</span>';

		} else {

			$out = '';

		}

		return $out;

	}


	/**
	 * [OPTIONAL] this is example, how to render specific column
	 *
	 * method name must be like this: "column_[column_name]"
	 *
	 * @param $item - row (key, value array)
	 * @return HTML
	 */
	function column_active($item) {

		if (isset($item['active']) && $item['active'] == 1) {

			$out = '<span style="color:green">' . esc_html__('Yes', 'datebook') . '</span>';

		} else {

			$out = '';

		}

		return $out;

	}


	/**
	 * [OPTIONAL] this is example, how to render column with actions,
	 * when you hover row "Edit | Delete" links showed
	 *
	 * @param $item - row (key, value array)
	 * @return HTML
	 */
	function column_name($item) {

		$menu = Options_Framework_Admin::menu_settings();

		if ( isset( $menu['menu_referrer_slug'] ) ) {
			$menu_referrer_slug = $menu['menu_referrer_slug'];
		}

		// links going to /admin.php?page=[your_plugin_page][&other_params]
		// notice how we used $_REQUEST['page'], so action will be done on current page
		// also notice how we use $this->_args['singular'] so in this example it will
		// be something like &custom_field=2
		$actions = array(
			'edit' => sprintf('<a href="admin.php?page=%s&subpage=edit_form&referrercode=%s">%s</a>', esc_attr($menu_referrer_slug), esc_attr($item['referrercode']), esc_html__('Edit', 'datebook')),
			'delete' => sprintf('<a onclick="return confirm(\' %s \')" href="admin.php?page=%s&tab=settings&action=delete&referrercode=%s">%s</a>', esc_html__('Do you really want to delete it?', 'datebook'), esc_attr($menu_referrer_slug), esc_attr($item['referrercode']), esc_html__('Delete', 'datebook')),
		);

		// if foreign language do not exist, then show title in English
		$item['name'] = isset($item['name']) ? $item['name'] : '';

		return sprintf('%s %s',
			esc_attr($item['name']),
			$this->row_actions($actions)
		);
	}


	/**
	 * [OPTIONAL] This method processes bulk actions
	 * it can be outside of class
	 * it can not use wp_redirect coz there is output already
	 * in this example we are processing delete action
	 * message about successful deletion will be shown on page in next part
	 */
	function process_bulk_action() {

		if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete'){

			$get_slug = isset($_REQUEST['referrercode']) ? $_REQUEST['referrercode'] : '';

			if (isset($get_slug)) {

				// Update entire array
				// Get entire array
				$get_profile_custom_fields = get_option('datebook_referral_options');

				$all_custom_fields = $get_profile_custom_fields;

				if ('delete' === $this->current_action()) {

					foreach ($all_custom_fields as $key => $value) {

						// Remove field from array
						if ($key == $get_slug) {
							unset($all_custom_fields[$key]);
						}

					}

					//Update entire array
					update_option('datebook_referral_options', $all_custom_fields);

				}
			}
		}
	}


	/**
	 * [REQUIRED] This method return columns to display in table
	 * you can skip columns that you do not want to show
	 * like content, or description
	 *
	 * @return array
	 */
	function get_columns() {

		$columns = array(
			'name' => esc_html__('Referrer name', 'datebook'),
			'referrercode' => esc_html__('Code', 'datebook'),
			'slug' => esc_html__('Referrer website', 'datebook'),
			'sendtoreferrerurl' => esc_html__('Send a request to this site', 'datebook'),
			'period' => esc_html__('Cookies period', 'datebook'),
			'profile_id' => esc_html__('Profile ID', 'datebook'),
			'active' => esc_html__('Active', 'datebook')
		);

		return $columns;

	}


	/**
	 * [REQUIRED] This is the most important method
	 *
	 * It will get rows from database and prepare them to be showed in table
	 */
	function prepare_items() {

		$empty_array = array('referrercode' => '', 'name' => '', 'slug' => '', 'sendtoreferrerurl' => '', 'profile_id' => '', 'period' => '', 'active' => '');

		$per_page = 300; // constant, how much records will be shown per page

		$columns = $this->get_columns();
		$hidden = array();
		$sortable = $this->get_sortable_columns();

		// here we configure table headers, defined in our methods
		$this->_column_headers = array($columns, $hidden, $sortable);

		// [OPTIONAL] process bulk action if any
		$this->process_bulk_action();

		//Get entire array
		$datebook_referrers_array = get_option('datebook_referral_options');
		
		if(isset($datebook_referrers_array) && !empty($datebook_referrers_array) && is_array($datebook_referrers_array)){
		
			$get_all_referrers = array();

			foreach($datebook_referrers_array as $code => $function){
				$function = array_merge($empty_array, $function);
				$get_all_referrers[] = array('referrercode' => $function['referrercode'],'name' => $function['name'], 'slug' => $function['slug'], 'sendtoreferrerurl' => $function['sendtoreferrerurl'], 'profile_id' => $function['profile_id'], 'period' => $function['period'], 'active' => $function['active']);
			}

			if(is_array($get_all_referrers) && !empty($get_all_referrers)){

				// will be used in pagination settings
				$total_items = count($get_all_referrers);

				// prepare query params, as usual current page, order by and order direction
				$paged = isset($_REQUEST['paged']) ? ($per_page * max(0, intval($_REQUEST['paged']) - 1)) : 0;

				// Define $items array
				// notice that last argument is ARRAY_A, so we will retrieve array
				$this->items = $get_all_referrers;

				// configure pagination
				$this->set_pagination_args(array(
					'total_items' => $total_items, // total items defined above
					'per_page' => $per_page, // per page constant defined at top of method
					'total_pages' => ceil($total_items / $per_page) // calculate pages count
				));
			}
		}
	}
}


class Options_Framework_Referrer {

	/**
	 * List page handler
	 *
	 * This function renders our custom table
	 * Notice how we display message about successfull deletion
	 * Actualy this is very easy, and you can add as many features
	 * as you want.
	 *
	 * Look into /wp-admin/includes/class-wp-*-list-table.php for examples
	 */
	static function register_handler() {

		if (isset($_REQUEST['subpage']) && $_REQUEST['subpage'] == 'edit_form') {

			self::referrer_form_page_handler();

		} else {
			
			$table_options = new DateBook_Referrers_Options();
			$table_options->prepare_items();

			$table = new DateBook_Referrers_List();
			$table->prepare_items();

			$message = '';
			if ($table->current_action() === 'delete') {
				if(is_array($_REQUEST['profile_id'])){
					$message = sprintf(esc_html__('Item deleted: %d', 'datebook'), count($_REQUEST['profile_id']));
				} else {
					$message = sprintf(esc_html__('Item deleted: %s', 'datebook'), $_REQUEST['profile_id']);
				}

			}

			$menu = Options_Framework_Admin::menu_settings();

			if ( isset( $menu['menu_referrer_slug'] ) ) {
				$menu_referrer_slug = $menu['menu_referrer_slug'];
			}
			
			//Get the active tab from the $_GET param
			$default_tab = null;
			$tab = isset($_GET['tab']) ? $_GET['tab'] : $default_tab;

			?>

			<div class="wrap">

				<h1 class="wp-heading-inline"><?php esc_html_e('Referral system', 'datebook'); ?></h1>

				<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_referrer_slug . '&subpage=edit_form');?>"><?php esc_html_e('Create Referral link', 'datebook')?></a>
			
				<hr class="wp-header-end">
				
				<?php if (!empty($notice)): ?>

					<div id="notice" class="error">
						<p><?php echo esc_attr($notice); ?></p>
					</div>

				<?php endif;?>

				<?php if (!empty($message)): ?>

					<div id="message" class="updated">
						<p><?php echo esc_attr($message) ?></p>
					</div>

				<?php endif;?>


				<div id="message" class="bg-white">
					<p><?php esc_html_e('Create referral links and share them in a variety of ways. The easiest and most common ways are usually through email, social media, different blogs, or through text message. Referral links allow you to see exactly where visitors came from, when were referred, when registered, profile ID, and where to send a notification request about registration.', 'datebook'); ?></p>
				</div>

				<nav class="nav-tab-wrapper">
					<a href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_referrer_slug);?>" class="nav-tab <?php if($tab===null):?>nav-tab-active<?php endif; ?>"><?php esc_html_e('Visitors', 'datebook'); ?></a>
					<a href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_referrer_slug . '&tab=settings');?>" class="nav-tab <?php if($tab==='settings'):?>nav-tab-active<?php endif; ?>"><?php esc_html_e('Referral links', 'datebook'); ?></a>
				</nav>

				<div class="tab-content">
				
					<?php
					
					switch($tab) :
						case 'settings': $table_options->display();
							break;
						default: $table->display();
							break;
					endswitch;
					
					?>

				</div>

			</div>

	        <?php

		}
	}


	/**
	 * Form for adding andor editing row
	 * ============================================================================
	 *
	 * In this part you are going to add admin page for adding andor editing items
	 * You cant put all form into this function, but in this example form will
	 * be placed into meta box, and if you want you can split your form into
	 * as many meta boxes as you want
	 *
	 * http://codex.wordpress.org/Data_Validation
	 * http://codex.wordpress.org/Function_Reference/selected
	 */

	/**
	 * Form page handler checks is there some data posted and tries to save it
	 * Also it renders basic wrapper in which we are callin meta box render
	 */
	static function referrer_form_page_handler() {

		$message = '';
		$notice = '';

		// here we are verifying does this request is post back and have correct nonce
		if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], basename(__FILE__))) {
			
			// validate data, and if all ok save item to database
			// if id is zero insert otherwise update
			$item = stripslashes_deep(self::validate_form($_POST));

			if ($item['success'] === true) {

				//Update entire array
				//Get entire array
				$all_referrals = get_option('datebook_referral_options');

				//Alter the options array appropriately
				$all_referrals[$item['referrercode']] = $item;
				
				//Update entire array
				$result = update_option('datebook_referral_options', $all_referrals);

				if( $result === FALSE){
					$notice = esc_html__('Data have NOT been saved', 'datebook');
				} else {
					$message = esc_html__('Item was successfully saved', 'datebook');
				}


			} else {

				// if $item not true it contains error message(s)
				$notice = $item['error_message'];

			}

		} else {

			// if this is not post back we load item to edit or give new one to create
			$item = '';

			if (isset($_REQUEST['referrercode'])) {

				//Get entire array
				$all_referrals = get_option('datebook_referral_options');

				//Alter the options array appropriately
				if(isset($all_referrals[$_REQUEST['referrercode']])){
					$item = $all_referrals[$_REQUEST['referrercode']];
				}

				if (!$item) {

					$item = '';
					$notice = esc_html__('Item not found', 'datebook');

				}
			}
		}

		// here we adding our custom meta box
		add_meta_box('refferer_form_meta_box_meta_box', 'Edit Referral link', array( __CLASS__ , 'referrer_form'), 'refferer_fields', 'normal', 'default');
	
		$menu = Options_Framework_Admin::menu_settings();

		$menu_referrer_slug = ( isset( $menu['menu_referrer_slug'] ) ) ? $menu['menu_referrer_slug'] : '';

    ?>

		<div class="wrap">

			<h1 class="wp-heading-inline"><?php esc_html_e('Edit Referral link', 'datebook')?></h1>

			<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_referrer_slug);?>"><?php esc_html_e('Back to Visitors', 'datebook')?></a> 
			
			<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_referrer_slug . '&tab=settings');?>"><?php esc_html_e('Back to Referral links', 'datebook')?></a>

			<hr class="wp-header-end">

			<?php if (!empty($notice)): ?>

				<div id="notice" class="error">
					<p><?php echo esc_attr($notice); ?></p>
				</div>

			<?php endif;?>

			<?php if (!empty($message)): ?>

				<div id="message" class="updated">
					<p><?php echo esc_attr($message) ?></p>
				</div>

			<?php endif;?>

			<form id="form" method="POST">

				<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
				
				<?php if (!empty($item['referrercode'])) { ?>
				
				<input type="hidden" name="referrercode" value="<?php echo esc_attr($item['referrercode']); ?>"/>
				
				<?php } ?>

				<div class="metabox-holder" id="poststuff">
					<div id="post-body">
						<div id="post-body-content">

							<?php /* And here we call our custom meta box */ ?>
							<?php do_meta_boxes('refferer_fields', 'normal', $item); ?>

							<input id="submit" class="button-primary" type="submit" name="submit" value="<?php esc_html_e('Save', 'datebook')?>" />

						</div>
					</div>
				</div>

			</form>

		</div>

	<?php

	}


	/**
	 * This function renders our custom meta box
	 * $item is row
	 *
	 * @param $item
	 */
	static function referrer_form($item) {

		// Let's lowercase, strip, clean, remove spaces
		$referrercode = isset($item['referrercode']) ? $item['referrercode'] : DateBook_Utilities::datebook_random_symbols(12);

		$website_link = get_site_url(NULL, '/');

		$referral_query_link = add_query_arg( array(
            'ref' => $referrercode
		), $website_link );


		?>

		<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
			<tbody>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="active"><?php esc_html_e('Enable', 'datebook'); ?></label>
					</th>
					<td><input id="datebook-active"  name="active" value="1" type="checkbox" <?php if (isset($item['active']) && $item['active'] == 1) { echo ' checked="checked"'; } ?> /> <label for="datebook-active"><?php esc_html_e('Yes', 'datebook'); ?></label></td>
				</tr>


				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="referrerurl"><?php echo esc_html__( 'Referral link', 'datebook' ); ?></label>
					</th>
					<td><strong><?php echo esc_url($referral_query_link); ?></strong><br>
					<em style="clear:both; width:100%; display:block"><?php esc_html_e('Use this link in banners or referring sites', 'datebook'); ?></em></td>
				</tr>


				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="name"><?php echo esc_html__( 'Referrer name', 'datebook' ); ?></label>
					</th>
					<td><input id="name" name="name" type="text" style="width: 95%" value="<?php if (isset($item['name'])) { echo esc_attr($item['name']); } ?>" size="50" class="code" placeholder="<?php echo esc_html__( 'Enter title', 'datebook' ); ?>" required /></td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="referrercode"><?php echo esc_html__( 'Referral code', 'datebook' ); ?></label>
					</th>
					<td><input id="referrercode" name="referrercode" type="text" style="width: 95%" value="<?php echo esc_attr($referrercode); ?>" size="50" class="code" placeholder="<?php echo esc_html__( 'Create code', 'datebook' ); ?>: A512SW9045" required /></td>
				</tr>


				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="slug"><?php esc_html_e('Website URL of referrer', 'datebook'); ?> (<?php esc_html_e('optional', 'datebook'); ?>)</label>
					</th>
					<td><input id="slug" name="slug" type="text" style="width: 95%" value="<?php if (isset($item['slug'])) { echo esc_attr($item['slug']); } ?>" size="50" class="code" placeholder="https://www.google.com" />

					<em style="clear:both; width:100%; display:block"><?php esc_html_e('You can enter the exact URL where requests should come from, or leave this field empty', 'datebook'); ?>. <?php esc_html_e('Example', 'datebook'); ?>: https://www.google.com</em>
						
					</td>
				</tr>

				<tr class="form-field" style="border-top: 1px solid #C8C8C8">
					<th valign="top" scope="row">
						<label for="sendtoreferrerurl"><?php esc_html_e('Send a notification to here', 'datebook'); ?> (<?php esc_html_e('optional', 'datebook'); ?>)</label>
					</th>
					<td><input id="sendtoreferrerurl" name="sendtoreferrerurl" type="text" style="width: 95%" value="<?php if (isset($item['sendtoreferrerurl'])) { echo esc_attr($item['sendtoreferrerurl']); } ?>" size="50" class="code" placeholder="https://www.website.com/?referrerback=yes" />

					<em style="clear:both; width:100%; display:block"><?php esc_html_e('If you want to send a notification to a website about successful registration, enter the URL where the request should be sent.', 'datebook'); ?>. <?php esc_html_e('Example', 'datebook'); ?>: https://website/?referrerback=yes</em>
						
					</td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="parameters_back"><?php esc_html_e('Add all parameters from referrer to notification', 'datebook'); ?></label>
					</th>
					<td><input id="datebook-parameters_back"  name="parameters_back" value="1" type="checkbox" <?php if (isset($item['parameters_back']) && $item['parameters_back'] == 1) { echo ' checked="checked"'; } ?> /> <label for="datebook-parameters_back"><?php esc_html_e('Yes', 'datebook'); ?></label> 

					<em style="clear:both; width:100%; display:block"><?php esc_html_e('Referrers can add their own parameters to referral links, in this case you can add all those parameters to the notification', 'datebook'); ?>. <?php esc_html_e('Example', 'datebook'); ?>: https://website/?referrerback=yes&amp;click_id=32432454&amp;coupon=A234O78</em>
					</td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="profile_id"><?php esc_html_e('Add Profile ID to notification', 'datebook'); ?></label>
					</th>
					<td><input id="datebook-profile_id"  name="profile_id" value="1" type="checkbox" <?php if (isset($item['profile_id']) && $item['profile_id'] == 1) { echo ' checked="checked"'; } ?> /> <label for="datebook-profile_id"><?php esc_html_e('Yes', 'datebook'); ?></label>
					</td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="datebook-textarea"><?php echo esc_html__( 'Additional parameters', 'datebook' ); ?></label>
					</th>
					<td>
					
					<?php
					
					$urlparts = parse_url($website_link);
					$domain = $urlparts['host'];
					
					?>

						<textarea id="datebook-textarea" name="field_items" rows="4" placeholder="from=<?php echo esc_attr($domain); ?>"><?php if (!empty($item['field_items'])) { echo esc_attr($item['field_items']); } ?></textarea>
						
						<em style="clear:both; width:100%; display:block"><?php esc_html_e('You can add your own parameters to the notification link', 'datebook'); ?>. <?php esc_html_e('Example', 'datebook'); ?>: from=<?php echo esc_attr($domain); ?> (<?php esc_html_e('Result', 'datebook'); ?>: https://www.website.com/?from=<?php echo esc_attr($domain); ?>)</em>

						<p><?php esc_html_e('Enter items as many as you wish. After each item press ENTER.', 'datebook'); ?></p>

					</td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="datebook-period"><?php echo esc_html__( 'Period', 'datebook' ); ?></label>
					</th>
					<td><input id="datebook-period" name="period" type="text" style="width: 150px" value="<?php if (isset($item['period'])) { echo esc_attr($item['period']); } ?>" size="5" maxlength="5" class="code" placeholder="<?php echo esc_html__( 'Enter number', 'datebook' ); ?>" /> <label for="datebook-period"><?php esc_html_e('days', 'datebook'); ?></label><br />

					<p><?php esc_html_e('How many days cookies should be kept in the browser of visitor', 'datebook'); ?>. <?php esc_html_e('Default', 'datebook'); ?>: 1 <?php esc_html_e('year', 'datebook'); ?></p>

					</td>
				</tr>


				<tr class="form-field" style="border-top: 1px solid #C8C8C8">
					<th valign="top" scope="row">
						<label for="sendemail"><?php esc_html_e('Send notification to referrer', 'datebook'); ?></label>
					</th>
					<td><input id="datebook-sendemail"  name="sendemail" value="1" type="checkbox" <?php if (isset($item['sendemail']) && $item['sendemail'] == 1) { echo ' checked="checked"'; } ?> /> <label for="datebook-sendemail"><?php esc_html_e('Yes', 'datebook'); ?></label>
					</td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="emailaddress"><?php esc_html_e('Email address', 'datebook'); ?></label>
					</th>
					<td><input id="emailaddress" name="emailaddress" type="text" style="width: 95%" value="<?php if (isset($item['emailaddress'])) { echo esc_attr($item['emailaddress']); } ?>" size="50" class="code" placeholder="" /></td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="emailsubject"><?php esc_html_e('Email subject', 'datebook'); ?></label>
					</th>
					<td><input id="emailsubject" name="emailsubject" type="text" style="width: 95%" value="<?php if (isset($item['emailsubject'])) { echo esc_attr($item['emailsubject']); } ?>" size="50" class="code" placeholder="<?php esc_html_e('Example', 'datebook'); ?>: Referral visitor registered on yourwebsite.com" /></td>
				</tr>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="datebook-emailtext"><?php echo esc_html__( 'Email text', 'datebook' ); ?></label>
					</th>
					<td>

						<textarea id="datebook-emailtext" name="emailtext" rows="7" placeholder="Hello!&#10;&#10;Profile on your referral link has been registered&#10;Profile: [profile_permalink]&#10;&#10;Kind regards"><?php if (!empty($item['emailtext'])) { echo esc_attr($item['emailtext']); } ?></textarea>
						
						<p><?php esc_html_e('Shortcodes', 'datebook'); ?>:
						<ul>
							<li>[profile_permalink] - <?php esc_html_e('creates a profile page permalink', 'datebook'); ?></li>
						</ul>
						</p>
						
						

					</td>
				</tr>

			</tbody>
		</table>

	<?php
	
	}


	/**
	 * Simple function that validates data and retrieve bool on success
	 * and error message(s) on error
	 *
	 * @param $item
	 * @return bool|string
	 */
	static function validate_form($item) {

		$data = array();
		$messages = array();

		if(is_array($item)) {

			if(!empty($item['type']) && $item['type'] == 'text' && !empty($item['name'])){

				$item['name'] = stripslashes(sanitize_textarea_field($item['name']));

			} else {

				$messages[] = esc_html__('Title is required', 'datebook');

			}

			if(empty($item['field_items'])){
				$messages[] = esc_html__('Field Items are required', 'datebook');
			}

			$data = $item;

			if (is_array($data)) {

				$data['success'] = true;

			} else {

				$data['success'] = false;
				$data['error_message'] = esc_html__( 'Data have not been saved', 'datebook' );

			}

		} else {

			$data['success'] = false;
			$data['error_message'] = esc_html__( 'Data have not been saved', 'datebook' );

		}

		return $data;

	}

}