<?php
/**
 * Display notices in admin.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/* -------------------------------------------------------
 * Create functions notice_html_install
 * ------------------------------------------------------- */
class Yolo_Notice_Install {

	private $product_id = 'yolo-kidzone';

	private $install_option_group = 'yolo_option_install_group';

	private $install_option_name = 'yolo_option_install_name';

	private $install_section_id = 'yolo_option_section_id';

	private $option_metabox = array();

	public function __construct() {
		add_action( 'plugins_loaded', array( $this, 'my__construct' ) );
	}
	public function my__construct() {

		if ( current_user_can( 'manage_options' ) ) {

			//add_action( 'admin_notices', array( $this, 'notice_html_install' ) );
			add_action( 'admin_menu', array( $this, 'admin_menus' ) );

			// -- Call setting fields
			add_action('admin_init', array( $this, 'yolo_settings_fields'));
			// -- set ajax
			add_action( 'wp_ajax_yolo_setup', array( $this, 'yolo_setup' ) );
			if ( isset( $_GET['page'] ) == 'yolo-setup' ) :

				add_action( 'admin_head', array( $this, 'load_enqueue_style_setup' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'load_enqueue_script_setup' ) );

			endif;

			require dirname( __FILE__ ) . '/yolo-import.php';

		}
	}

	public function load_enqueue_style_setup() {

		?>
		<style type="text/css" media="screen">
			mark.yes {
				background-color: transparent;
				color: #7ad03a;
			}
			mark.error {
				background-color: transparent;
				color: #a00;
			}
			mark.error span:hover {
				cursor: pointer;
			}
			table.widefat {
				margin-bottom: 20px;
			}
		</style>
		<?php

	}

	public function load_enqueue_script_setup() {

		wp_register_script( 'setup-install', YOLO_PLUGIN_ASSETS_URI . '/js/min/yolo.setup.install.min.js', array( 'jquery'), null, true );
		wp_enqueue_script('setup-install');

		wp_register_script( 'setup-install-demo', YOLO_PLUGIN_ASSETS_URI . '/js/min/yolo.setup.install.demo.js' );
		wp_enqueue_script('setup-install-demo');

		wp_register_style( 'setup-style', YOLO_PLUGIN_ASSETS_URI . '/css/yolo-setup.css' );
		wp_enqueue_style( 'setup-style' );


		wp_localize_script( 'setup-install', 'yoloSetup', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
		wp_localize_script( 'setup-install-demo', 'yoloSetupDemo', 
			array( 
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'notice'   => __( 'Do you want to continue this action?', 'yolo-kidzone' ),
				'warning'  => __( 'Please waiting, not exit page.', 'domain' ),
				'ajax_nonce' => wp_create_nonce( 'install-demo' ),
				'img_ajax_load' => YOLO_PLUGIN_ASSETS_URI . '/images/ajax-loader.gif'
				) 
			);

	}
	
	// -- Notice html
	
	public function notice_html_install() {
		if ( !$this->yolo_get_option('disable_notice_install') && !isset($_GET['page']) == 'yolo-setup' ) :

			?>
		<div id="message" class="updated notice is-dismissible">
			<p><strong><?php echo sprintf( __('Welcome to %s,', 'yolo-kidzone'), wp_get_theme($this->product_id)->get('Name') ); ?></strong></p>
			<p><?php _e('If it is the first time you install this theme, you should go and check the basic setting.', 'yolo-kidzone'); ?></p>
			<p class="submit">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=yolo-setup' ) ); ?>" class="button-primary">
					<?php _e( 'Go to Quick Setup', 'yolo-kidzone' ); ?>
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=yolo-setup&action=skip' ) ); ?>" class="button">
					<?php _e( 'Skip Setup', 'yolo-kidzone' ); ?>
				</a>
			</p>
		</div>
		<?php

		endif;
	}

	// -- Create page
	public function admin_menus() {
		add_menu_page ( 
			__( 'Yolo Settings', 'yolo-kidzone' ), 
			__( 'Yolo Settings', 'yolo-kidzone' ), 
			'manage_options', 
			'yolo-setup', 
			array( $this, 'yolo_page_setup' ),
			'dashicons-admin-generic'
			);
	}

	// -- Processsing setup
	public function yolo_setup() {
		global $wpdb;

			// ----
		
		$page['title'] = $_POST['title'];
		$page['content'] = isset( $_POST['content'] ) && !empty( $_POST['content'] ) ? $_POST['content'] : '';
		$page['page_template'] = isset( $_POST['page_template'] ) && !empty( $_POST['page_template'] ) ? $_POST['page_template'] : 'default';
		$page['setting_group'] = isset( $_POST['setting_group'] ) && !empty( $_POST['setting_group'] ) ? $_POST['setting_group'] : '';
		$page['setting_key'] = isset( $_POST['setting_key'] ) && !empty( $_POST['setting_key'] ) ? $_POST['setting_key'] : '';

			// -----

		$post_data = array(
			'post_title' => $page['title'],
			'post_content'  => $page['content'],
			'post_status' => 'publish',
			'post_type'   => 'page',
			'post_author' => get_current_user_id()
			);

				$id_page = wp_insert_post( $post_data ); // -- Insert post
				
				if( !is_wp_error( $id_page ) ) {
					update_post_meta($id_page, '_wp_page_template',  $page['page_template']); //- Set page template
					if( !empty( $page['setting_key'] ) ) {
						if( !empty( $page['setting_group'] ) ) {
							$setting_group = get_option( $page['setting_group'] );
							$setting_group[ $page['setting_key'] ] = $id_page;
							update_option( $page['setting_group'], $setting_group );
						} else {
							$setting_value = get_option( $page['setting_key'] );
							update_option( $page['setting_key'], $id_page );
						}
					}

					$post = get_post($id_page);
					echo json_encode( array( 'id' => __('Done', 'yolo-kidzone'), 'slug' => $post->post_name ) );
				}
				exit;
			}

	// -- Add option
			public function yolo_add_option( $name ) {
				$options = array_merge( get_option( 'yolo_setup', array() ), $name );
				update_option( 'yolo_setup', $options );
			}

	// -- Get option
			public function yolo_get_option( $name ) {
				$options = get_option( 'yolo_setup' );
				return $options[$name];
			}

	// -- Tab menu
			public function yolo_tab_menu( $current = 'general' ) {

				$tabs = array(
					//'general'   => __("Quick Setup", 'yolo-kidzone'), 
					'import_demo'  => __("Import Demo", 'yolo-kidzone')
					);
				$html =  '<h2 class="nav-tab-wrapper">';
				foreach( $tabs as $tab => $name ) :
					
					$class = ($tab == $current) ? 'nav-tab-active' : '';
				$html .=  '<a class="nav-tab ' . $class . '" href="?page=yolo-setup&tab=' . $tab . '">' . $name . '</a>';
				
				endforeach;
				$html .= '</h2>';
				echo $html;

			} 

	// -- Page setup
			public function yolo_page_setup() {
				
				if ( isset( $_GET['page'] ) == 'yolo-setup' ) :

					if ( isset( $_GET['tab'] ) ) :

						$tab = $_GET['tab'];

					else :

						$tab = 'general';

					endif;

					$this->yolo_tab_menu( $tab );

					switch ( $tab ) {
						// case 'general':
						// $this->yolo_general_options();
						// break;
						case 'import_demo':
						$this->yolo_import_demo_options();
						break;
						default:
						$this->yolo_import_demo_options();
						break;
					}

					endif;
				}

	// -- OPTION
				
			// -- Option client
				public function yolo_option_client() {
					$settings_field_name = $this->get_product_field_name();
					$settings_group_id = $this->product_id . '-license-settings-group';
					$options = get_option( $settings_field_name );
					?>
					<table class="widefat" cellspacing="0" id="client">
						<thead>
							<tr>
								<th colspan="3" data-export-label="<?php _e( 'License', 'yolo-kidzone' ); ?>">
									<label>
										<?php _e( 'License', 'yolo-kidzone' ); ?>
									</label>
								</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td data-export-label="<?php _e( 'License key', 'yolo-kidzone' ); ?>"><?php _e( 'License key:', 'yolo-kidzone' ); ?></td>
								<td class="help">
									<a href="#" title="<?php _e( 'The purchase code you get from ThemeForest', 'yolo-kidzone' ); ?>" class="help_tip">[?]</a>
								</td>
								<td>
									<input type='text' name='license_key' value='<?php echo $options['license_key']; ?>' class='regular-text'>
									<input type='hidden' name='email' value='<?php echo str_replace( 'http://', '', home_url( )); ?>' class='regular-text'>
									<span><?php echo sprintf( __( '<a target="_blank" href="%s">How to get License key?</a>', 'yolo-kidzone' ), 'http://support.yolotheme.com/wp-content/uploads/2015/07/HowToGetPurchaseCode.png' ) ?></span>
								</td>
							</tr>
						</tbody>
					</table>
					<?php
				}

				public function yolo_get_page_id_by_template( $page_template = '' ) {

					$pages = get_pages(array(
						'meta_key' => '_wp_page_template',
						'meta_value' => $page_template
						));

					if( $pages ){
						return $pages[0]->ID;
					}
					return false;

				}

			// -- Option page
				public function yolo_option_page() {
					
					?>
					<table class="widefat" cellspacing="0">
						<thead>
							<tr>
								<th colspan="5" data-export-label="<?php _e( 'Required Pages', 'yolo-kidzone' ); ?>"><?php _e( 'Required Pages', 'yolo-kidzone' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php
							global $wpdb;

							$list_pages = array(
								array(
									'title'         => __('Front Page' , 'yolo-kidzone'),
									'content'       => '',
									'page_template' => '',
									'help'          => __('The Homepage', 'yolo-kidzone'),
									'setting'       => array( 
										'group' => '',
										'key'   => 'show_on_front',
										'value' => 'page',
										'url'   => admin_url( 'options-reading.php' )
										),
									),
								array(
									'title'         => __('Member' , 'yolo-kidzone'),
									'content'       => '[yolo_member_account]',
									'page_template' => '',
									'help'          => __('The main page for all the action of Employer and Candidate', 'yolo-kidzone'),
									'setting'       => array( 
										'group' => 'yolo_member',
										'key'   => 'manage_page_id',
										'url'   => admin_url( 'edit.php?post_type=yolo_job&page=manage_yolo_job&tab=member' )
										),
									),
								array(
									'title'         => __('Packages' , 'yolo-kidzone'),
									'content'       => '[yolo_job_package_list]',
									'page_template' => '',
									'help'          => __('The page for Employer to choose Job Package', 'yolo-kidzone'),
									'setting'       => array( 
										'group' => 'job_package',
										'key'   => 'package_page_id',
										'url'   => admin_url( 'edit.php?post_type=yolo_job&page=manage_yolo_job&tab=job_package' )
										),
									),
								array(
									'title'         => __('Post Job' , 'yolo-kidzone'),
									'content'       => '',
									'page_template' => 'page-post-job.php',
									'help'          => __('The page for Job posting', 'yolo-kidzone'),
									'setting'       => array(),
									),
								array(
									'title'         => __('Post Resume' , 'yolo-kidzone'),
									'content'       => '',
									'page_template' => 'page-post-resume.php',
									'help'          => __('The page for Resume posting', 'yolo-kidzone'),
									'setting'       => array(),
									),
								);

if( !Yolo_Job::use_woocommerce_package() ) {
	unset($list_pages[2]);
}

foreach ($list_pages as $list_page => $page) :
	echo '<tr>';

$get_id = null;
$get_page = null;

									// Check the setting first
$setting = $page['setting'];
$setting_value = null;
$setting_result = '';
if( isset( $setting ) && !empty( $setting ) && is_array($setting) && !empty( $setting['key'] ) ) :
	if( !empty( $setting['group'] ) ) {
		$setting_group = get_option( $setting['group'] );
		$setting_value = is_array( $setting_group ) && isset( $setting_group[ $setting['key'] ] ) ? $setting_group[ $setting['key'] ] : null;
	} else {
		$setting_value = get_option( $setting['key'] );
	}

	if( $setting_value == null ) :
		$setting_result = 'missing';
	else :
		$setting_result = 'false';
	if( isset( $setting['value'] ) && $setting['value'] == $setting_value ) {
		$setting_result = 'true';
	} elseif( is_numeric( $setting_value ) ) {
		$get_id = absint( $setting_value );
		$get_page = get_post( $get_id );
		if( !empty( $get_page ) && $get_page->post_type == 'page' ) {

													// There's setting, check if the setting satisfy the other condition: page template and page content.
			if( ( isset( $page['page_template'] ) && !empty( $page['page_template'] ) && $page['page_template'] == yolo_get_post_meta( $get_id, '_wp_page_template' ) ) 
				|| ( isset( $page['content'] ) && !empty( $page['content'] ) && strpos( $get_page->post_content, $page['content'] ) !== false  ) ) {
				$setting_result = 'true';
		}
	}
}
endif;


if( !empty( $get_id ) ) {
	echo "<td data-export-label='{$page['title']}'>";
	echo "<a href='" . get_edit_post_link( $get_id ) . "' title='{$page['title']}' target='_blank'>{$page['title']}</a>";
	echo "</td>";
} else {
	echo "<td data-export-label='{$page['title']}'>{$page['title']}</td>";
}
if( isset( $page['help'] ) && !empty( $page['help'] ) ) {
	echo '<td class="help">';
	echo '	<a href="#" class="help_tip" title="' . $page['help'] . '">[?]</a>';
	echo '</td>';
}

echo '<td>';
if( $setting_result == 'missing' ) {
	echo "	<mark class='error'>" . __( 'Missing setting', 'yolo-kidzone' ) . "</mark>";
} elseif( $setting_result == 'false' ) {
	echo "<mark class='error'>" . __( 'Wrong', 'yolo-kidzone' );
	if( !empty( $page['content'] ) ) {
		echo ' - ' . sprintf( __( 'Page should contains %s', 'yolo-kidzone' ), $page['content'] );
	} elseif ( !empty( $page['page_template'] ) ) {
		echo ' - ' . sprintf( __( 'Page should have template %s', 'yolo-kidzone' ), $page['page_template'] );
	}
	echo "</mark>";
} else {
	echo "<mark class='yes'>" . __('Done', 'yolo-kidzone');
	if( !empty( $get_id ) && !empty( $get_page ) ) {
		echo " - /{$get_page->post_name}/";
	}
	echo '</mark>';
}
echo '</td>';

echo '<td>';
if( $setting_result !== 'true' && ( !empty( $page['content'] ) || !empty( $page['page_template'] ) ) ) {
	echo '	<div class="button button-primary">';
	echo '		<span class="correct-setting" data-title="' . $page['title'] . '" data-content="' . $page['content'] . '" data-page-template="' . $page['page_template'] . '" data-setting-group="' . $setting['group'] . '" data-setting-key="' . $setting['key'] . '">' . __('Correct now', 'yolo-kidzone') . '</span>';
	echo '	</div>';
}
echo '</td>';
echo '<td>';
if( $setting_result != 'true' && isset( $setting['url']) && !empty( $setting['url'] ) ) {
	echo '	<div class="button">';
	echo "		<a href='{$setting['url']}' title='{$page['title']}' target='_blank'>" . __("Edit setting", "yolo") . "</a>";
	echo '	</div>';
}
echo '</td>';

else :
	if ( !empty($page['page_template']) ) :
		$get_id = $this->yolo_get_page_id_by_template($page['page_template']);
	$get_page = !empty( $get_id ) ? get_post( $get_id ) : null;
	
	if( !empty( $get_id ) && !empty( $get_page ) ) {

		echo "<td data-export-label='{$page['title']}'>";
		echo "<a href='" . get_edit_post_link( $get_id ) . "' title='{$page['title']}' target='_blank'>{$page['title']}</a>";
		echo "</td>";
		if( isset( $page['help'] ) && !empty( $page['help'] ) ) {
			echo '<td class="help">';
			echo '	<a href="#" class="help_tip" title="' . $page['help'] . '">[?]</a>';
			echo '</td>';
		}
		echo '<td>';
		echo "	<mark class='yes'>" . __('Done', 'yolo-kidzone') . " - /{$get_page->post_name}/</mark>";
		echo '</td>';
	} else {
		echo "<td data-export-label='{$page['title']}'>{$page['title']}</td>";
		if( isset( $page['help'] ) && !empty( $page['help'] ) ) {
			echo '<td class="help">';
			echo '	<a href="#" class="help_tip" title="' . $page['help'] . '">[?]</a>';
			echo '</td>';
		}
		echo '<td>';
		echo "	<mark class='error'>" . sprintf( __( 'You need to create a page with template %s', 'yolo-kidzone' ), $page['page_template'] ) . "</mark>";
		echo '</td>';
		echo '<td>';
		echo '	<div class="button button-primary">';
		echo '		<span class="correct-setting" data-title="' . $page['title'] . '" data-content="' . $page['content'] . '" data-page-template="' . $page['page_template'] . '">' . __('Correct now', 'yolo-kidzone') . '</span>';
		echo '	</div>';
		echo '</td>';
		echo '<td></td>';
	}
	else :
		echo '<td colspan="4"></td>';
	endif;
	endif;

	echo '</tr>';
	endforeach;
	
	?>
</tbody>
</table>
<?php
}

		// -- Tools options
public function yolo_import_demo_options() {

	$list_demo = array(
		array(
			'name' => __( 'Kidzone', 'yolo-kidzone'),
			'img'  => YOLO_PLUGIN_PATH . "/admin/importer/data-demo/kidzone/screenshot.jpg",
			'file' => 'kidzone'
			)
		);

		?>
		<table class="widefat" cellspacing="0" style="width: 99%;">
			<thead>
				<tr>
					<th colspan="1" data-export-label="<?php _e( 'Settings', 'yolo-kidzone' ); ?>">
						<label class="hide_main">
							<?php _e( 'Settings', 'yolo-kidzone' ); ?>
						</label>
					</th>
				</tr>
			</thead>
			<tbody id="yolo_main_select">
				<tr>
					<td>
						<input type='checkbox' data-id='import_post' id='import_post' value='1' checked /> <?php _e( 'Import Post', 'yolo-kidzone' ); ?>
					</td>
				</tr>
				<tr>
					<td>
						<input type='checkbox' data-id='import_nav' id='import_nav' value='1' checked /> <?php _e( 'Import Nav Menu', 'yolo-kidzone' ); ?>
					</td>
				</tr>
				<tr>
					<td>
						<input type='checkbox' data-id='import_comment' id='import_comment' value='1' checked /> <?php _e( 'Import Comment', 'yolo-kidzone' ); ?>
					</td>
				</tr>
				<tr>
					<td>
						<input type='checkbox' data-id='import_revslider' id='import_revslider' value='1' checked /> <?php _e( 'Import Revslider', 'yolo-sofani' ); ?>
					</td>
				</tr>
			</tbody>
		</table>
		<div id="yolo_tools">

			<!-- [ MAIN ] -->
			<div id="process_import"></div>
			<div class="theme-browser rendered" style="margin-top: 20px;">
				<div class="themes">
					<?php foreach ($list_demo as $id => $demo) : ?>
						<div class="yolo-load-ajax"><img src ="<?php echo YOLO_PLUGIN_ASSETS_URI.'/images/ajax-loader.gif';?>" alt = "Loader">
							<span><?php echo esc_html('Please wait a few minute...')?></span>
						</div>
						<div class="theme" tabindex="0">
							<div class="theme-screenshot">
								<img src="<?php echo $demo['img']; ?>" alt="" />
							</div>
							<div class="yolo-load-ajax"></div>
							<div class="theme-id-container">
								<h3 class="theme-name" id="yolo-<?php echo $demo['file']; ?>-name"><?php echo $demo['name']; ?></h3>
								<div class="theme-actions yolo-buton-actions">
									<button class="install-demo button-primary button button-secondary activate"
									data-name="<?php echo $demo['file']; ?>"
									data-import-post="true"
									data-import-nav="true"
									data-import-comment="true"
									data-import-revslider = "true"
									><?php _e( 'Install Demo', 'yolo-kidzone' ); ?></button>
								</div>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
				<br class="clear">
			</div>
			
		</div><!-- /#yolo_tools -->

		<?php

	}

	// -- Setting fields
	
	public function get_product_field_name() {
		return $this->product_id . '-license-settings';
	}
	
	public function yolo_settings_fields() {

		register_setting( $this->install_option_group, $this->install_option_name );

		add_settings_section( 
			$this->install_section_id, 
			'Title Section', 
			'',
			$this->install_option_group 
			);
		add_settings_field( 
			$this->product_id . '-page',
			'Page', 
			array( $this, 'render_settings_section' ),
			$this->install_option_group,
			$this->install_section_id 
			);


	}

		/**
         * Renders the description for the settings section.
         */
		public function render_settings_section() {
		}

	// -- Options fields
		public function yolo_options_fields() {

			$this->option_metabox[] = array(

				'id' => 'general_options',
				'title' => _e( 'General Options', 'yolo-kidzone' )

				);

			return $this->option_metabox;			

		}

	}
	new Yolo_Notice_Install;