<?php
/**
 * Install countries and cities into custom countries table.
 *
 * @class DateBook_Install_Countries_Cities
 * @author Pagick Themes
 * @since 1.6
 */
	 

/**
 * 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_Countries_List_Table class that will display our custom table
 * records in nice table
 */
class DateBook_Countries_List_Table extends WP_List_Table {

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

		global $status, $page;

		parent::__construct(array(
			'singular' => 'city',
			'plural' => 'cities',
		));

	}


	/**
	 * [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_translation($item) {

		return '<em>' . esc_attr($item['translation']) . '</em>';

	}


	/**
	 * [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 = '';
			
		}

		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_countries_slug'] ) ) {
			$menu_countries_slug = $menu['menu_countries_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 &city=2
		$actions = array(
			'edit' => sprintf('<a href="admin.php?page=%s&subpage=edit_form&id=%s">%s</a>', esc_attr($menu_countries_slug), esc_attr($item['id']), esc_html__('Edit', 'datebook')),
			'delete' => sprintf('<a onclick="return confirm(\' %s \')" href="admin.php?page=%s&action=delete&id=%s">%s</a>', esc_html__('Do you really want to delete it? If it has subitems then all of them will be deleted too.', 'datebook'), esc_attr($menu_countries_slug), esc_attr($item['id']), esc_html__('Delete', 'datebook')),
		);

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

		return sprintf('<a href="admin.php?page=%s&subpage=countries_and_cities&action=show_children&parent_id=%d">%s</a> %s',
			esc_attr($menu_countries_slug),
			esc_attr($item['id']),
			esc_attr($item_name),
			$this->row_actions($actions)
		);
	}


	/**
	 * [REQUIRED] this is how checkbox column renders
	 *
	 * @param $item - row (key, value array)
	 * @return HTML
	 */
	function column_cb($item) {

		return sprintf('<input type="checkbox" name="id[]" value="%s" />', esc_attr($item['id']));

	}


	/**
	 * [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(
			'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
			'name' => esc_html__('Name', 'datebook'),
			'slug' => esc_html__('Slug', 'datebook'),
			'translation' => esc_html__('Translation', 'datebook'),
			'active' => esc_html__('Enable', 'datebook')
		);

		return $columns;

	}


	/**
	 * [OPTIONAL] This method return columns that may be used to sort table
	 * all strings in array - is column names
	 * notice that true on name column means that its default sort
	 *
	 * @return array
	 */
	function get_sortable_columns() {

		$sortable_columns = array(
			'slug' => array('slug', true),
		);

		return $sortable_columns;

	}


	/**
	 * [OPTIONAL] Return array of bult actions if has any
	 *
	 * @return array
	 */
	function get_bulk_actions() {

		$actions = array(
			'disable' => 'Disable',
			'enable' => 'Enable'
		);

		return $actions;

	}


	/**
	 * Delete all regions and cities
	 */
	function select_all_regions_and_cities($ids) {

		global $wpdb;
		
		$all_ids_array = array();

		// notice that last argument is ARRAY_A, so we will retrieve array
		$all_regions_array = $wpdb->get_results($wpdb->prepare($this->countries_items(). " WHERE parent_id = %d", $ids), ARRAY_A);

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

			$all_ids_array[] = $value['id'];

			$all_cities_array = $wpdb->get_results($wpdb->prepare($this->countries_items(). " WHERE parent_id = %d", $all_regions_array[$key]['id']), ARRAY_A);

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

				$all_ids_array[] = $value['id'];

			}
		}

		return $all_ids_array;

    }

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

		$ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array();
		
		if ($ids && is_array($ids)) {
			
			global $wpdb;
			
			$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix
			
			// how many entries will we select?
			$how_many = count($ids);

			// prepare the right amount of placeholders
			// if you're looing for strings, use '%s' instead
			$placeholders = array_fill(0, $how_many, '%d');

			// glue together all the placeholders...
			// $format = '%d, %d, %d, %d, %d, [...]'
			$format = implode(', ', $placeholders);
			
			if (!empty($ids)) {

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

					// and put them in the query
					$query = "UPDATE $table_name SET active = 0 WHERE id IN($format)";

				} else if ('enable' === $this->current_action()) {

					// and put them in the query
					$query = "UPDATE $table_name SET active = 1 WHERE id IN($format)";

				}
			
				// now you can get the results
				$wpdb->query( $wpdb->prepare($query, $ids) );
				
			}
		}
	}


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

		global $wpdb;
		
		$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

		$countries_items_query = "SELECT * FROM $table_name";

		return $countries_items_query;

	}


	/**
	 * Select all countries and regions
	 */
	function select_all_countries_and_regions() {

		global $wpdb;

		$all_ids_array = array();

		// Define $items array
		// notice that last argument is ARRAY_A, so we will retrieve array
		$countries_array = $wpdb->get_results($wpdb->prepare($this->countries_items(). " WHERE parent_id = %d ORDER BY slug ASC", 0), ARRAY_A);

		foreach($countries_array as $key => $value){
			
			$all_ids_array[] = $value;

			// notice that last argument is ARRAY_A, so we will retrieve array
			$regions_array = $wpdb->get_results($wpdb->prepare($this->countries_items(). " WHERE parent_id = %d", $value['id']), ARRAY_A);

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

				$all_ids_array[] = $value;

			}
		}

		return $all_ids_array;

	}


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

		$countries_and_regions_array = $this->select_all_countries_and_regions();

		$countries_and_cities_out = '';
		$countries_and_cities_out .= '<select name="parent_id">';
		$countries_and_cities_out .= '<option value="0">' . esc_html__('Select country or region', 'datebook') . '</option>';
		
		foreach($countries_and_regions_array as $key => $value){

			if (isset($value['parent_id']) && $value['parent_id'] > 0) { $indent_sign = '- '; } else { $indent_sign = ''; }

			if ($parent_item_id == $value['id']) { $selected = ' selected="selected" '; } else { $selected = ''; }

			$value['name'] = maybe_unserialize( $value['name'] );
			// if foreign language do not exist, then show title in English
			$value['name'] = isset($value['name'][DATEBOOK_WPLANG]) ? $value['name'][DATEBOOK_WPLANG] : $value['name']['en_US'];
			
			$countries_and_cities_out .= '<option value="' . esc_attr($value['id']) . '" '.$selected.'>' . $indent_sign . '' . esc_attr($value['name']) . '</option>';
		}
		$countries_and_cities_out .= '</select>';
		
		return $countries_and_cities_out;

    }


    /*
     * Method that processes data on Countries page
     *
     */
    function process_data() {

		$ids = isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id']) ? $_GET['id'] : 0;
		
		if ($ids > 0) {
			
			if ($this->current_action() === 'delete') {

				global $wpdb;

				$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

				// if country deleted then delete regions too
				$sub_ids = $this->select_all_regions_and_cities($ids);

				if (!empty($sub_ids)) {

					// how many entries will we select?
					$how_many = count($sub_ids);

					// prepare the right amount of placeholders
					// if you're looing for strings, use '%s' instead
					$placeholders = array_fill(0, $how_many, '%d');

					// glue together all the placeholders...
					// $format = '%d, %d, %d, %d, %d, [...]'
					$format = implode(', ', $placeholders);

					// and put them in the query
					$query = "DELETE FROM $table_name WHERE id IN($format)";

					$wpdb->query( $wpdb->prepare($query, $sub_ids) );

				}

				// prepare the right amount of placeholders
				// if you're looing for strings, use '%s' instead
				$placeholders = array_fill(0, 1, '%d');

				// glue together all the placeholders...
				// $format = '%d, %d, %d, %d, %d, [...]'
				$format = implode(', ', $placeholders);

				// and put them in the query
				$query = "DELETE FROM $table_name WHERE id IN($format)";

				// now you can get the results
				$wpdb->query( $wpdb->prepare($query, $ids) );

			}
		}
		
		if (isset($_POST['table']) && $_POST['table'] == 'truncate' && $this->current_action() === 'delete' && isset($_POST['trancate_text']) && $_POST['trancate_text'] == 'YES'){

			global $wpdb;

			$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

			$wpdb->query("TRUNCATE TABLE $table_name");

		}
	}


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

		$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

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

		$where_clause = (isset($_REQUEST['action']) && $_REQUEST['action'] == 'show_children' && isset($_REQUEST['parent_id'])) ? $_REQUEST['parent_id'] : 0;

		// will be used in pagination settings
		$total_items = $wpdb->get_var($wpdb->prepare("SELECT COUNT(id) FROM $table_name WHERE parent_id = %d", $where_clause));

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

		$orderby = (isset($_REQUEST['orderby']) && in_array($_REQUEST['orderby'], array_keys($this->get_sortable_columns()))) ? $_REQUEST['orderby'] : 'slug';
		$order = (isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('asc', 'desc'))) ? $_REQUEST['order'] : 'asc';
        
		// Define $items array
		// notice that last argument is ARRAY_A, so we will retrieve array
		$this->items = $wpdb->get_results($wpdb->prepare($this->countries_items(). " WHERE parent_id = %d ORDER BY $orderby $order LIMIT %d OFFSET %d", $where_clause, $per_page, $paged), ARRAY_A);

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

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

		global $wpdb;

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

			self::datebook_countries_and_cities_editform();

		} else {

			$table_name = strtolower($wpdb->prefix) . 'datebook_countries';
			$check_datebook_countries = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_name));

			if ($check_datebook_countries != $table_name) {
				
			?>

				<div class="wrap">

					<h1 class="wp-heading-inline"><?php esc_html_e('Database Table is not created yet!', 'datebook')?></h1>

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

					<div id="message" class="below-h1">
						<p><?php esc_html_e('Countries and Cities (MySQL) table is not created yet.', 'datebook')?></p>
						<p><?php esc_html_e('Please, go to DateBook -> Theme Installer. Click on the 1. Install button to install all countries and cities.', 'datebook')?></p>
					</div>
					
				</div>
			
			<?php 
			
			} else {
			
				$table = new DateBook_Countries_List_Table();
				$table->process_data();
				$table->prepare_items();

				$message = '';
				if ($table->current_action() === 'delete'){
					$message = esc_html__('Item has been deleted', 'datebook');
				}

				$menu = Options_Framework_Admin::menu_settings();

				if ( isset( $menu['menu_countries_slug'] ) ) {
					$menu_countries_slug = $menu['menu_countries_slug'];
				}
		
				?>
		
				<div class="wrap">
			
					<h1 class="wp-heading-inline"><?php esc_html_e('Countries and Cities', 'datebook')?></h1>
				
					<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_countries_slug . '&subpage=edit_form&createcountry=1');?>"><?php esc_html_e('Add Country', 'datebook')?></a> 

					<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_countries_slug . '&subpage=edit_form&createcountry=0');?>"><?php esc_html_e('Add Region or City', 'datebook')?></a>
			
					<hr class="wp-header-end">
			
					<div id="message" class="bg-white">
						<p><?php esc_html_e('On this page you can add, edit, delete countries and cities.', 'datebook')?></p>
						<p><?php esc_html_e('Click on a country to see regions. Then click on a region to see cities. (Hierarchy: countries -> regions -> cities)', 'datebook')?></p>
					</div>
			
					<?php 
				
					if (!empty($message)) {

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

					}

					?>

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

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

					</form>
					
					<?php

					$list = $wpdb->get_results("SELECT * FROM $table_name");
					
					if($list){
					
					?>
					
						<h3><?php esc_html_e('Delete all records on one click', 'datebook')?></h3>
						<p><?php esc_html_e('Your database has some records in the Countries table. You can delete them on one click.', 'datebook')?></p>
						
						<form method="POST" action="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=' . $menu_countries_slug . '&action=delete&table=truncate');?>">

							<input type="hidden" name="nonce" value="<?php echo wp_create_nonce('truncate')?>"/>
							<input type="hidden" name="action" value="delete"/>
							<input type="hidden" name="table" value="truncate"/>
							
							<?php esc_html_e('Type in the word', 'datebook')?> YES <input type="text" name="trancate_text" value=""/> 

							<input class="button action" type="submit" name="submit" value="<?php esc_html_e('Delete', 'datebook')?>" />

						</form>

					<?php } ?>

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

		global $wpdb;

		$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

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

		// this is default $item which will be used for new records
		$default = array(
			'id' => 0,
			'name' => '',
			'slug' => '',
			'translation' => '',
			'parent_id' => '',
			'level' => '',
			'active' => '',
		);

		// here we are verifying does this request is post back and have correct nonce
		if (isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
			
			// combine our default item with request params
			$item = shortcode_atts($default, $_REQUEST);
			
			// validate data, and if all ok save item to database
			// if id is zero insert otherwise update
			$item_valid = self::datebook_validate_city($item);
			
			if ($item_valid === true) {
				
				global $wp_locale_all;
				
				if (empty($item['slug'])) {
					$item['slug'] = $item['name']['en_US'];
				} else {
					$item['slug'] = $item['slug'];
				}

				// Let's lowercase, strip, clean, remove spaces
				$item['slug'] = DateBook_Utilities::datebook_makeslug($item['slug']);

				// 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 || isset($item['name'][$language['locale']]) && $item['name'][$language['locale']] != ''){
						$languages_array[$language['locale']] = $wp_locale_all[$language['locale']];
					}
				}


				$item_translation = '';
				foreach ( $languages_array as $language_key => $language_name ) {
					$item_translation .= $language_name . ': ' . stripslashes(sanitize_text_field($item['name'][$language_key])) . '; ';
				}

				$item['translation'] = $item_translation;

				$item['name'] = maybe_serialize( wp_unslash($item['name']) );

				if ($item['id'] == 0) {
					
					$result = $wpdb->insert($table_name, $item);
					$item['id'] = $wpdb->insert_id;
					if ($result) {
						$message = esc_html__('Item was successfully saved', 'datebook');
					} else {
						$notice = esc_html__('There was an error while saving item', 'datebook');
					}

				} else {

					if( $wpdb->update($table_name, $item, array('id' => $item['id'])) === FALSE){
						//show failure message
						$notice = esc_html__('Oops! Something went wrong. Data has NOT been saved.', 'datebook');
					} else {
						// show success message
						$message = esc_html__('Item was successfully updated', 'datebook');
					}

				}

			} else {

				// if $item_valid not true it contains error message(s)
				$notice = $item_valid;

			}

		} else {

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

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

            	$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $_REQUEST['id']), ARRAY_A);

				if (!$item) {

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

				}
			}
		}

		// here we adding our custom meta box
		add_meta_box('countries_and_cities_form_meta_box', 'Edit Country, Region or City', array( __CLASS__ , 'datebook_countries_and_cities_form_meta_box_handler'), 'city', 'normal', 'default');
	
		$menu = Options_Framework_Admin::menu_settings();

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

    ?>

		<div class="wrap">

			<h1 class="wp-heading-inline"><?php esc_html_e('Countries and Cities', 'datebook')?></h1>

			<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page='.esc_attr($menu_countries_slug));?>"><?php esc_html_e('Back to Countries and Cities', '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__))?>"/>
				<input type="hidden" name="id" value="<?php echo esc_attr($item['id']); ?>"/>

				<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('city', '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 datebook_countries_and_cities_form_meta_box_handler($item) {
		
		global $wp_locale_all;
		
		$item['name'] = maybe_unserialize( $item['name'] );
		
		// 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 || isset($item['name'][$language['locale']]) && $item['name'][$language['locale']] != ''){
				$languages_array[$language['locale']] = $wp_locale_all[$language['locale']];
			}
		}

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

				<?php 				

				foreach ( $languages_array as $language_key => $language_name ) {

				?>

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

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="parent_id"><?php esc_html_e('Country or Region', 'datebook'); ?></label>
					</th>
					<td>
					
					<?php
					
					if ((isset($_GET['createcountry']) && $_GET['createcountry'] == 1) || (!isset($_GET['createcountry']) && isset($item['parent_id']) && $item['parent_id'] == 0)) {

						esc_html_e('Country cannot have higher category', 'datebook');

					} else {

						$all_countries = new DateBook_Countries_List_Table;
						echo $all_countries->get_all_countries_and_cities($item['parent_id']);

					}
					
					?>
					
					</td>
				</tr>
				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="level"><?php esc_html_e('Is it Region or City?', 'datebook'); ?></label>
					</th>
					<td>

					<?php

					if ((isset($_GET['createcountry']) && $_GET['createcountry'] == 1) || (!isset($_GET['createcountry']) && isset($item['parent_id']) && $item['parent_id'] == 0)) {

						esc_html_e('This is country and cannot be Region or City', 'datebook');

					} else { 

					?>

						<input id="datebook-level-1" name="level" value="1" type="radio"<?php if (isset($item['level']) && $item['level'] == 1) { echo ' checked'; } ?> /><label for="datebook-level-1"><?php esc_html_e('Region', 'datebook'); ?></label>
						<input id="datebook-level-2" name="level" value="2" type="radio"<?php if (isset($item['level']) && $item['level'] == 2) { echo 'checked'; } ?> /><label for="datebook-level-2"><?php esc_html_e('City', 'datebook'); ?></label>

					<?php } ?>
					
					</td>
				</tr>

				<?php

				if (isset($item['slug']) && $item['slug'] != ''){
					
					$flag_url = DATEBOOK_URL . 'assets/images/flags/' . $item['slug'] . '.png';

					?>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="slug"><?php esc_html_e('Slug', 'datebook'); ?></label>
					</th>
					<td><input id="datebook-country-slug" type="text" name="slug" value="<?php echo esc_attr($item['slug']); ?>" style="width:80%" disabled /> <button class="datebook-country-slug-button" type="button"><?php esc_html_e('Enable', 'datebook'); ?></button></td>
				</tr>

				<?php /*?><tr class="form-field">
					<th valign="top" scope="row">
						<label for="flag_url"><?php echo esc_html__( 'Path to flag icon', 'datebook' ); ?></label>
						
					</th>
					<td><input id="flag_url" name="flag_url" type="text" style="width: 95%" value="<?php if(isset($item['flag_url']) && $item['flag_url'] != '') { echo esc_url($item['flag_url']); } ?>" size="50" class="code" placeholder="<?php echo esc_html__( 'You may enter a path to a different flag icon', 'datebook' ); ?>" /><br>

					<?php echo esc_html__( 'Default icon', 'datebook' ); ?>: <?php echo esc_url($flag_url); ?>

					</td>
				</tr><?php */?>

				<?php } ?>

				<tr class="form-field">
					<th valign="top" scope="row">
						<label for="active"><?php esc_html_e('Enable', 'datebook'); ?></label>
					</th>
					<td><input id="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>

			</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 datebook_validate_city($item) {

		global $wp_locale_all;
		
		$messages = array();
				
		// 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 || isset($item['name'][$language['locale']]) && $item['name'][$language['locale']] != ''){
				$languages_array[$language['locale']] = $wp_locale_all[$language['locale']];
			}
		}

		foreach ( $languages_array as $language_key => $language_name ) {
			
			$language_key_name = $item['name'][$language_key];

			if (empty($language_key_name)) 
				$messages[] = sprintf( esc_html__( 'Title in %1$s is required', 'datebook' ), esc_attr($language_name) );
			
		}
		
		if(!empty($item['parent_id']) && !absint(intval($item['parent_id'])))  $messages[] = esc_html__('Parent can not be less than zero', 'datebook');

		if(!empty($item['parent_id']) && !preg_match('/[0-9]+/', $item['parent_id'])) $messages[] = esc_html__('Parent must be number', 'datebook');

		if (empty($messages)) return true;

		return implode('<br />', $messages);

	}

}