<?php
/**
 * Create Gateways form.
 *
 * @class DateBook_Gateways_Table
 * @author Pagick Themes
 * @since 3.4
 */
	 

/**
 * Define DateBook Table List
 * ============================================================================
 *
 * In this part you are going to define custom table list class,
 * that will display your database records in nice looking table
 *
 * http://codex.wordpress.org/Class_Reference/WP_List_Table
 * http://wordpress.org/extend/plugins/custom-list-table-example/
 */

if (!class_exists('WP_List_Table')) {

	require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');

}

/**
 * DateBook_Gateways_Table class that will display our custom table
 * records in nice table
 */
class DateBook_Gateways_Table extends WP_List_Table {

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

		global $status, $page;

		parent::__construct(array(
			'singular' => 'gateway',
			'plural' => 'gateways',
		));
	}


	/**
	 * [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) {
		
		if ($column_name == 'field_items'){
			
			// if foreign language do not exist, then show title in English
			$item[$column_name] = isset($item[$column_name . '_' . DATEBOOK_WPLANG]) ? $item[$column_name . '_' . DATEBOOK_WPLANG] : $item[$column_name . '_en_US'];

			return esc_attr($item[$column_name]);
			
		} else {
			
			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_active($item) {
		
		if (isset($item['active']) && $item['active'] == 1) {
			
			$active_out = '<span style="color:green">' . esc_html__('Yes', 'datebook') . '</span>';
			
		} else {
			
			$active_out = '<span style="color:red">' . esc_html__('No', 'datebook') . '</span>';
			
		}

		return $active_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_gateways_slug'] ) ) {
			$menu_gateways_slug = $menu['menu_gateways_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 &gateway=2
		$actions = array(
			'edit' => sprintf('<a href="admin.php?page=%s&subpage=edit_form&slug=%s">%s</a>', esc_attr($menu_gateways_slug), esc_attr($item['slug']), esc_html__('Edit', 'datebook'))
		);

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

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


	/**
	 * [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__('Name', 'datebook'),
			'active' => esc_html__('Enable', 'datebook')
		);

		return $columns;

	}


	/**
	 * It will get rows from database and prepare them to be showed as select
	 */
	function get_all_gateways($gateway_type) {

		// Define $items array
		// notice that last argument is ARRAY_A, so we will retrieve array
		$gateways_array = array('title' => 'Title', 'text' => 'Text', 'textarea' => 'Textarea', 'radio' => 'Radio buttons', 'checkbox' => 'Checkboxes', 'select' => 'Select (dropdown)');

		$gateways_out = '';
		$gateways_out .= '<select name="type">';
		$gateways_out .= '<option value="0">' . esc_html__('Select field type', 'datebook') . '</option>';
		
		foreach($gateways_array as $key => $value){

			if ($gateway_type == $key) { $selected = ' selected="selected" '; } else { $selected = ''; }

			$gateways_out .= '<option value="' . esc_attr($key) . '" '.$selected.'>' . esc_attr($value) . '</option>';
		}
		$gateways_out .= '</select>';
		
		return $gateways_out;

    }


	/**
	 * [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 $datebook_payment_gateways;

		$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);

		//Get saved gateways
		$gateways_options = get_option('datebook_gateways');

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

			$gateway_active = isset($gateways_options[$key]['enabled']) && $gateways_options[$key]['enabled'] == 1 ? 1 : 0;

			$get_gateways[] = array('slug' => $key, 'name_en_US' => $value, 'active' => $gateway_active);

		}

		// will be used in pagination settings
		$total_items = isset($get_gateways) && is_array($get_gateways) ? count($get_gateways) : 0;

		// 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_gateways;

		// 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 DateBook_Payment_Gateways {

	/**
	 * 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 gateways_page_handler() {

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

			self::datebook_gateways_option_form_page_handler();

		} else {

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

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

			$menu = Options_Framework_Admin::menu_settings();

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

			?>

			<div class="wrap">

				<h1 class="wp-heading-inline"><?php esc_html_e('Gateways', 'datebook')?></h1>
				
					<hr class="wp-header-end">
			
					<div id="message" class="bg-white">
						<p><?php esc_html_e('On this page you can edit gateway settings', 'datebook')?></p>
					</div>
			
					<?php 
				
					if (!empty($message)) {

						echo '<div id="message" class="updated below-h2"><p> ' . esc_attr($message) . '</p></div>';

					}

					?>

					<form id="gateways-table" method="POST">
					
						<input type="hidden" name="page" value="<?php if ( isset($menu_gateways_slug) ) { echo esc_attr($menu_gateways_slug); } ?>"/>

						<?php $table->display() ?>

					</form>

				</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 datebook_gateways_option_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_data = self::datebook_validate_gateway($_POST);

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

				$gateways_options = get_option('datebook_gateways');

				$item = $item_data['form_fields'];
				
				if (!empty($item['datebook_gateway_slug'])){

					$datebook_gateway_slug = $item['datebook_gateway_slug'];
					
					$DateBook_Payment_Gateway_Class = "DateBook_Payment_Gateway_$datebook_gateway_slug";

					$load_gateway = new $DateBook_Payment_Gateway_Class();
					$gateways_options[$datebook_gateway_slug] = $load_gateway->datebook_save_settings();

				} else {

					$gateways_options[$item['slug']] = $item;

				}

				$result = update_option( 'datebook_gateways', $gateways_options );

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


			} else {

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

			}
			
		} else {
			
			// if this is not post back we load item to edit or give new one to create
			$item = array();

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

				$get_gateway_slug = (isset($_REQUEST['slug'])) ? $_REQUEST['slug'] : 'nothing';

				//Get entire array
				$item = get_option('datebook_gateways');
				$item = isset($item[$get_gateway_slug]) ? $item[$get_gateway_slug] : '';

				if (!$item) {

					$notice = esc_html__('Attention: Gateway not saved yet', 'datebook');

				}

				$item = array('slug' => $get_gateway_slug);

			}
		}

		// here we adding our custom meta box
		add_meta_box('gateways_form_meta_box', 'Edit Gateway', array( __CLASS__ , 'datebook_gateways_option_edit'), 'gateway', 'normal', 'default');
	
		$menu = Options_Framework_Admin::menu_settings();

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

    ?>

		<div class="wrap">

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

			<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page='.esc_attr($menu_gateways_slug));?>"><?php esc_html_e('Back to Gateways', '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['slug'])) { ?>
				
				<input type="hidden" name="slug" value="<?php echo esc_attr($item['slug']); ?>"/>
				
				<?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('gateway', 'normal', $item); ?>

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

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

			</form>

			<?php if(isset($_GET['slug']) && $_GET['slug'] == 'paypal_standard'){ ?>

				<h2 class="title">Helpful articles</h2>

				<h3>Here’s how to cancel a subscription or recurring payment:</h3>
				<ul>
					<li>1.Go to www.paypal.com and log in to your account.</li>
					<li>2.Click ‘Profile’ near the top of the page.</li>
					<li>3.Select ‘My money'.</li>
					<li>4.In the ‘My pre-approved payments’ section, click ‘Update'.</li>
					<li>5.Select the merchant whose agreement you want to cancel and click ‘Cancel’.</li>
					<li>6.Click ‘Cancel Profile’ to confirm your request</li>
				</ul>

				<h3>How to cancel a subscription (recurring payment) on Paypal</h3>
				<p><a href="https://support.jmir.org/hc/en-us/articles/115004750788-How-to-cancel-a-subscription-recurring-payment-on-Paypal" target="_blank">https://support.jmir.org/hc/en-us/articles/115004750788-How-to-cancel-a-subscription-recurring-payment-on-Paypal</a></p>

			<?php } ?>

		</div>

	<?php

	}
	

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

		global $wp_locale_all;

		// get languages
		$languages_array = array();

		$languages_array['en_US'] = esc_html__( 'English', 'datebook' );

		$languages = DateBook_Localization::datebook_all_available_language_files();

		foreach($languages as $language) {
			if($language['checked'] == 1){
				$languages_array[$language['locale']] = $wp_locale_all[$language['locale']];
			}
		}

		if(isset($item['slug'])){
			
			$datebook_gateway_slug = $item['slug'];
			
			$DateBook_Payment_Gateway_Class = "DateBook_Payment_Gateway_$datebook_gateway_slug";

			$load_gateway = new $DateBook_Payment_Gateway_Class();
			$load_gateway->display_setting_page();

		}

	}


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

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

		if(is_array($item)) {
			
			$data['form_fields'] = $item;

			if (is_array($data)) {

				$data['success'] = true;
				
			} else {

				$data['success'] = false;
				$data['error_message'] = esc_html__( 'Oops! Something went wrong.', 'datebook' );

			}

		} else {

			$data['success'] = false;
			$data['error_message'] = esc_html__( 'Oops! Something went wrong.', 'datebook' );

		}

		return $data;

	}

}