<?php
/**
 * Themes administration panel.
 *
 * @package WordPress
 * @subpackage Administration
 */
/** WordPress Administration Bootstrap */
require_once(dirname(__FILE__) . '/admin.php');

$selected_theme = get_option('sp_setup_selected_theme');

if (!current_user_can('switch_themes') && !current_user_can('edit_theme_options')) {
	wp_die('<h1>' . __('Cheatin&#8217; uh?') . '</h1>' . '<p>' . __('You are not allowed to edit theme options on this site.') . '</p>', 403);
}

global $sitepad;

$title = __('Manage Themes');
$parent_file = 'setup.php';

if (current_user_can('switch_themes')) {
	$themes = wp_prepare_themes_for_js();
} else {
	$themes = wp_prepare_themes_for_js(array(wp_get_theme()));
}
// r_print($themes);
require_once(ABSPATH . 'site-admin/admin-header.php');
//r_print($themes);

$category = optGET('category');

	echo '		
<div class="wrap">
	<div class="bg col-md-12">
	
<div class="theme-browser">
<div class="row">
	<div class="col-lg-2 col-md-2 submenu-item" style="border-left:1px #222 solid;">
		<p style="color:#f2ffff;margin-top:8px;margin-bottom:8px;font-size:16px;">Categories</p>
		<ul class="navbar-nav mr-auto" id="navigation-list">
			<li id="category_list_all" class="nav-item"><a class="all nav-link category-button' . (empty($category) ? ' active' : '') . '" style="font-size:14px;color:#aaaaaa;" href="' . admin_url('setup.php') . '" name="all">' . __('All') . '</a></li>';
		foreach($GLOBALS['sp_category'] as $slug => $cat){
			$cat_lang_slug = 'ThemeCategory_' . $slug;
			$cat_name = __($cat['en']);

			echo '<li id="category_list_' . $slug . '" class="nav-item mb-2"><a class="' . $slug . ' nav-link category-button p-0' . (!empty($category) && $category == $slug ? ' active' : '') . '" href="' . admin_url('setup.php?category=' . $slug) . '" style="color:#aaaaaa;font-size:14px;" name="' . $slug . '">' . $cat_name . '</a></li>';
		}
		echo '</ul>
	</div>
	<div class="themes-data col-lg-10 col-md-10">';
	
	?>			
		<center>
			<h1 class="mb-2">
				<span class="dashicons-before sme-dash-header dashicons-admin-appearance"></span> &nbsp; 
				<?php esc_html_e('Select a Theme'); ?>
				<span class="badge badge-secondary" style="font-size:15px;font-weight:300;top:-15px;">
					<?php echo count($themes); ?>
				</span>
			</h1>
		</center>

		<form id="theme-filter" method="post">
			<div class="row mb-2">
				<div class="col-sm-12 col-md-4" style="position:relative;">
					<input type="search" name="search" class="search-input form-control" value="<?php echo optREQ('q');?>" placeholder="Search Themes" autocomplete="off"/>							
					<div id="suggestion_list" class="suggestion_list" style="position:absolute !important; width:calc(100% - 30px);"></div> 
				</div>
				<div class="col-sm-12 col-md-8 mt-2">
					<div class="pavigation-menu">
						<div class="pagination-ui float-right">
							<?php
							// Filter the themes as per category selected
							
							$pagedurl = '';
							if (!empty($category)) {
								$pagedurl .= 'category=' . $category . '&';
								foreach ($themes as $id => $theme) {
									
									if ($category != strtolower($theme['category'])) {
										unset($themes[$id]);
									}
								}
							}

							// Filter the themes by search query
							$query = optGET('q');
							$query = rawurldecode($query);
							$searched = array();
							if (!empty($query)) {
								$pagedurl .= 'q=' . $query . '&';
								foreach ($themes as $id => $theme) {

									// Search by theme name
									if (substr(strtolower($theme['name']), 0, strlen($query)) === $query) {
										$searched[$id] = $theme;
									}

									// Search by Slug
									if (substr($theme['id'], 0, strlen($query)) === $query) {
										$searched[$id] = $theme;
									}

									// Search by tags
									$tags = explode(',', $theme['tags']);
									foreach ($tags as $x => $v) {
										if (substr($v, 0, strlen($query)) === $query) {
											$searched[$id] = $theme;
										}
									}
								}
							}

							// Pagination 
							$paged = (int) optGET('paged');
							$perpage = 21;

							// Don't Show Pagination if search value less than perpage
							if (!empty($searched)) {
								$total_pages = ceil(count($searched) / $perpage);
							} else {
								$total_pages = ceil(count($themes) / $perpage);
							}

							$current_page = 1;
							// Is it a valid page
							if (!empty($paged)) {
								$current_page = $paged;
							}

							if ($paged > $total_pages) {
								$current_page = $paged = 1;
							}

							if ($total_pages > 1) {

								echo '<ul class="pagination">';

								$pagedurl .= 'paged=';
								$previous = $current_page - 1;
								$next = $current_page + 1;

								if ($current_page > 1) {
									echo '<li class="page-item"><a href="' . admin_url('setup.php') . '" data-page="1" title="First" class="page-link" >&laquo;</a></li><li class="page-item"><a href="' . admin_url('setup.php' . ($previous > 1 ? '?' . $pagedurl . $previous : '')) . '" data-page="' . $previous . '" title="Previous" class="page-link" >&lt;</a></li>';
								}

								$start = 1;
								if ($current_page > 1) {
									$start = $current_page - 1;
								}

								$end = $current_page + 1;
								if ($end >= $total_pages) {
									$end = $total_pages;
								}

								for ($start; $start <= $end; $start++) {
									echo '<li class="page-item ' . ($start == $current_page ? ' active' : '') . '" ><a href="' . admin_url('setup.php' . ($start > 1 ? '?' . $pagedurl . $start : '')) . '" data-page="' . $start . '" title="' . $start . '" class="page-link" >' . $start . '</a></li>';
								}

								if ($current_page < $total_pages) {
									echo '<li class="page-item"><a href="' . admin_url('setup.php?' . $pagedurl . $next) . '" data-page="' . $next . '" title="Next" class="page-link" >&gt;</a></li><li><a href="' . admin_url('setup.php?' . $pagedurl . $total_pages) . '" data-page="' . $total_pages . '" title="Last" class="page-link" >&raquo;</a></li>';
								}
								echo '</ul>';
							} // Pagination ends
							?>
						</div>
					</div>
				</div>
			</div>
		</form>
		<?php echo error_handle($error, '100%', false, false, 'offset-sm-3 col-sm-6'); ?>

		<?php
		if (isset($_GET['activated'])):
			delete_option('todo_site_addr');
			if (isset($_GET['previewed'])) {
				?>
				<div id="message2" class="updated notice is-dismissible"><p><?php
						printf(__('Settings saved and theme activated. <a href="%s">Visit site</a>'), home_url('/'));
						?></p></div>
				<?php
			} else {

				$setup_done = get_option('sm_setup_done');

				// Is the setup and theme activation within 2 minutes ? Then we assume its just activated for the first time
				$just_activated = (time() - $setup_done) < 120 ? true : false;

				if (!empty($just_activated)) {

					$homepage = get_page_by_path('home');

					echo '  <div class="notice notice-success is-dismissible">
							<p>' . __('Your new theme has been activated. You will now be redirected to the') . ' ' . BRAND_SM_EDITOR . '</p>
							</div>
							<script>
							var gotourl = "' . admin_url('edit-page?post=' . $homepage->ID . '&action=edit') . '";
							//alert(gotourl);
							window.location = gotourl;
							</script>';
				} else {
					?>
					<div id="message2" class="updated notice is-dismissible"><p><?php
							printf(__('New theme activated. <a href="%s">Visit site</a>'), home_url('/'));
							?></p></div><?php
				}
			} elseif (isset($_GET['deleted'])):
			?>
			<div id="message3" class="updated notice is-dismissible"><p><?php
					_e('Theme deleted.');
					?></p></div>
			<?php
		elseif (isset($_GET['delete-active-child'])):
			?>
			<div id="message4" class="error"><p><?php
					_e('You cannot delete a theme while it has an active child theme.');
					?></p></div>
			<?php
		endif;
	
	
		echo '
		<div class="themes">';

		/*
		 * This PHP is synchronized with the tmpl-theme template below!
		 */
		if (empty($paged)) $paged = 1;

		$skip = ($paged - 1) * $perpage;
		$count = 0;
		$skipped = 0;

		// Display Search Query (condition added to search from all themes and not only search results)	
		if(!empty($searched)){
			$show_themes = $searched;
		} else {
			$show_themes = $themes;
		}
		// r_print($themes);
		$selected_themes = $unselected_themes = array();
		// Show the selected theme 1st and then others
		foreach($show_themes as $key => $theme){
			if($theme['id'] == $selected_theme){
				$selected_themes[] = $theme;
			}else{
				$unselected_themes[] = $theme;
			}
		}
		$show_themes = array_merge($selected_themes, $unselected_themes);
		// r_print($show_themes);
		foreach($show_themes as $theme):
			$aria_action = esc_attr($theme['id'] . '-action');
			$aria_name = esc_attr($theme['id'] . '-name');
		
			// We have already displayed themes allowed per page
			if ($count >= $perpage) {
				break;
			}

			// Are we to skip themes until we reach the themes for desired page
			if (!empty($skip) && $skipped < $skip) {
				$skipped++;
				continue;
			}

			$count++;
			
			$needs_premium = 0;
			if($theme['type'] > $sitepad['features']['themes']){
				$needs_premium = 1;
			}
			?>

			<div class="theme<?php echo ($theme['id'] == $selected_theme ? ' active' : '');?>" tabindex="0" id="<?php echo $theme['id'];?>" style="cursor:zoom-in">
				<?php 
				if(!empty($needs_premium)){
					echo '<div class="premium_themes">'.$sitepad['theme_levels'][$theme['type']].'</div>';
				}
				
				echo '<div id="'.$theme['id'].'" class="themes_details">';
				
				if(!empty($theme['screenshot'][0])){
					echo '<div class="theme-screenshot"><img src="'.$theme['screenshot'][0].'" alt="" /></div>';
				}else{
					echo '<div class="theme-screenshot blank"></div>';
				}
				
				if ($theme['id'] == $selected_theme) {
					echo '<h2 class="theme-name" style="height:auto" id="'.$aria_name.'">';
					/* translators: %s: theme name */
					printf(__('Selected: %s'), $theme['name']);
					echo '</h2>';
					
				} else {
					echo '<h2 class="theme-name" style="height:auto" id="'.$aria_name.'">'.$theme['name'].'
						<div style="float:right;margin-top:-5px;margin-bottom:-5px;">';
							
						if ($theme['id'] != $selected_theme) {
							if (!empty($needs_premium)) {
								echo '<a class="button button-secondary activate" href="'.admin_url('plans.php').'">'.__('View Plans').'</a>';
							} else {
								$active_url = str_replace('themes.php', 'setup.php', $theme['actions']['activate']);
								?>
								<form method="post">
									<input type="submit" id="theme_name" class="button button-secondary" name="select_theme" value="<?php _e( 'Select' ) ?>" />
									<input type="hidden" name="theme_name" value="<?php echo $theme['id']; ?>">
								</form>
								<?php
							}
						}
					echo '
						</div>
					</h2>';

				}
				?>
				</div>
				<div class="theme-actions display_button_yes" id="theme_action" style="width:100%;height:82%;text-align:center;top:41%">
					<span class="more-theme-details text-center" style="top: 50%;position: absolute;width: 50%;" ><?php
						_e('Theme Details');
						?></span>
				</div>

			</div>
			<?php
			endforeach;
			?>
			<br class="clear" />
		</div>
	</div>
</div>
</div>
<div class="theme-overlay"></div>
<div class="modal fade" id="details_modal" role="dialog">
	<div class="modal-dialog modal-lg" style="max-height:90vh;max-width:90vh;">	
	  <!-- Modal content-->
	  <div class="modal-content">		
		<div class="modal-body pt-0 pb-0" style="padding:3vh;">	
			<button type="button" class="close" data-dismiss="modal" >
				<span class="dashicons dashicons-dismiss" style="position:absolute;top:-5%;right:-3%;font-size:25px;color:#FFFFFF"></span>
			</button>
			<div class="p-0 detail_prev" style="border:2px solid #ffffff;border-radius:50%;background-color:#000000;position:absolute;top:50%;left:5vh;width:35px;height:35px;" id="" >
				<span class="dashicons dashicons-arrow-left-alt2"  style="font-size:27px;color:#ffffff;cursor:pointer;"></span>	
			</div>
			<div class="p-0 detail_next" style="border:2px solid #ffffff;border-radius:50%;background-color:#000000;position:absolute;top:50%;right:5vh;width:35px;height:35px;" id="" >
				<span class="dashicons dashicons-arrow-right-alt2"  style="font-size:27px;color:#ffffff;padding-left: 2px;cursor:pointer;"></span>	
			</div>	
			<div class="row m-0 pt-3">					
				<img src="" id="detail_img" style="max-height:84vh;min-height:84vh;min-width:84vh;max-height:84vh;">
			</div>
			<div class="row" style="border-top:1px solid #bcbcbc;padding:10px;">
				<div class="col-lg-8 col-md-8">
					<p class="detail_name theme-name mt-1" style="display:inline;font-size:20px;"></p>
					<p class="detail_category" style="display:inline;font-size:16px;"></p>
				</div>
				<div class="col-lg-2 col-md-2">
				<?php if(empty($SESS['no_demos'])){ ?>
					<a class="button button-secondary activate mt-1 detail_demo" style="background-color:#337AB7;color:#ffffff"href="" target="_blank"><?php _e('Demo');?></a>
				<?php } ?>
				</div>
				<div class="col-lg-2 col-md-2">
					<form method="post">
						<input type="submit" id="theme_name" class="button button-secondary mt-1" name="select_theme" value="<?php _e( 'Select' ) ?>" />
						<input type="hidden" name="theme_name" class="theme_name" value="">
					</form>	
				</div>
			</div>				
		</div>
	  </div>
	</div>
  </div>
<script>
	var data_details = <?php
		echo json_encode($themes, JSON_PRETTY_PRINT);
		?>;
	var sp_category = <?php
		echo json_encode($GLOBALS['sp_category'], JSON_PRETTY_PRINT);
		?>;
	var setup_url = <?php echo '"'.admin_url('setup.php').'"'; ?>;
	
	$(".detail_prev").on("click", function(){
		var curid =$(this).attr('id');
		sp_theme_details(curid);
	});
	$(".detail_next").on("click", function(){
		var curid =$(this).attr('id');
		sp_theme_details(curid);
	});
	$(".theme").on("click", function(){		
		var curid =$(this).attr('id');
		sp_theme_details(curid);
		$("#details_modal").modal("show");		
	});
	$(".theme input").on("click", function(){		
		//stop the event bubbling up to the parent
		event.stopPropagation();
	});
	
	function sp_theme_details(el) {
		 for (x in data_details) {
			var data = new Object();
			var cur = parseInt(x);
			if (el == data_details[x].id) {
				data.screenshot = data_details[x].screenshot[0];
				data.category = sp_category[data_details[x].category].en;
				data.active = data_details[x].active;
				data.actions = data_details[x].actions;
				data.actions.activate = data_details[x].actions.activate;
				data.name = data_details[x].name;
				data.description = data_details[x].description;
				data.version = data_details[x].version;
				data.tags = data_details[x].tags;
				data.parent = data_details[x].parent;
				data.actions['delete'] = data_details[x].actions.delete;
				data.authorAndUri = data_details[x].authorAndUri;
				data.demo = data.name.replace(' ', '_');
				if (data_details[cur - 1]) {
					$(".detail_prev").attr("id",data_details[cur - 1].id);
				}
				if (data_details[cur + 1]) {
					$(".detail_next").attr("id",data_details[cur + 1].id);
				}
				var select_url = data_details[x].actions.activate.replace("themes.php", "setup.php");
				$("#detail_img").attr("src",data.screenshot);
				$(".detail_name").text(data_details[x].name);
				$(".theme_name").val(data_details[x].id);
				$(".detail_category").text('/ '+ sp_category[data_details[x].category].en);
				$(".detail_select").attr("href", select_url);
				var demo_url = '<?php echo BRAND_SM_DEMOS; ?>';
				$(".detail_demo").attr("href", demo_url + data.name.replace(' ', '_'));
		
			}
		}
		
	}

	function close_smdetails() {
		jQuery(".theme-overlay").css('display', 'none');
	}

	function submit_search() {
		var a = jQuery(".search-input").val();
		if (a) {
			a = a.split(" ");
			show_searched_theme(a);
		}
		return false;
	}

	jQuery('.search-input').on('keyup', function (e) {

		var timer = null;
		clearTimeout(timer);
		var a = this.value;

		// On enter we will refresh the page and show only the themes matching search criteria
		if (e.keyCode == 13) {
			window.location.href = setup_url+"?q=" + a;
			return true;
		}

		// check value only after user stops typing
		timer = setTimeout(function () {
			if (e.keyCode == 8) {
				if (!a) {
					document.getElementById("suggestion_list").style.display = "none";
				}
			}

			if (a) {
				jQuery('#sm_assistant01').fadeOut('slow').css('margin-top', '20px');
			}

			if (a) {
				a = a.split(" ");//split if has space
				show_searched_theme(a); //search for theme
			}

		}, 1000);

	});

	function show_searched_theme(val) {
		var data = new Array();
		var arr = new Array();
		var vale = val.join(" "); // join split file
		var vale_slug = val.join(""); //join for slug
		vale_slug = vale_slug.toLowerCase();
		vale = vale.toLowerCase();
		//val = jQuery.trim(val);
		for (x in data_details) {

			var slug = data_details[x].id;
			var tags = data_details[x].tags;

			//search by theme name
			if ((data_details[x].name.substring(0, vale.length) === vale)) {
				data.push(data_details[x].id);
				arr.push(data_details[x].name);
			}

			//search by slug
			if ((data_details[x].id.substring(0, vale_slug.length) === vale_slug)) {
				data.push(data_details[x].id);
				arr.push(data_details[x].name);
			}

			tags_split = tags.split(",");

			//search by tags
			for (z in tags_split) {
				tags_split[z] = tags_split[z].trim();
				tags_split[z] = tags_split[z].toLowerCase();
				if (tags_split[z].lastIndexOf(vale, 0) === 0) {
					if (data.indexOf(data_details[x].id) == -1 && arr.indexOf(data_details[x].name) == -1) {
						data.push(data_details[x].id);
						arr.push(data_details[x].name);
					}
				}
			}
		}


		var txt = "";			// from here add value for search suggestion
		txt = '<ul id="list-suggestion" style="padding: 0px;margin-bottom:0 !important">';
		if (!jQuery.isEmptyObject(data)) {
			for (i in data) {
				txt += '<a href="'+setup_url+'?q='+data[i]+'" style="text-decoration: none;cursor:pointer;"><li>' + arr[i] + '</li></a>';
			}
		} else {
			txt += '<a class="inliner" href="javascript:void(0);"><li value="no-suggestion">No themes found with this search criteria</li></a>';
		}
		txt += '</ul>';
		document.getElementById("suggestion_list").innerHTML = txt;
		document.getElementById("suggestion_list").style.display = "block";	
	}

	jQuery(document).ready(function () {
		var show_theme = "<?php
		echo optGET('theme');
		?>";
		if (show_theme) {
			smtheme_details(show_theme);
		}
		
	});

</script>


<p class="no-themes"><?php
	_e('No themes found. Try a different search.');
?></p>

</div><!-- .wrap -->

<?php
require(ABSPATH . 'site-admin/admin-footer.php');
