<?php
/**
 * Themes administration panel.
 *
 * @package WordPress
 * @subpackage Administration
 */

/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );

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

if ( current_user_can( 'switch_themes' ) && isset($_GET['action'] ) ) {
	if ( 'activate' == $_GET['action'] ) {
		check_admin_referer('switch-theme_' . $_GET['stylesheet']);
		
		// SitePad pre switch theme function
		apply_filters('pre_switch_theme', $_GET['stylesheet']);
		
		$theme = wp_get_theme( $_GET['stylesheet'] );

		if ( ! $theme->exists() || ! $theme->is_allowed() ) {
			wp_die(
				'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
				'<p>' . __( 'The requested theme does not exist.' ) . '</p>',
				403
			);
		}

		switch_theme( $theme->get_stylesheet() );
		wp_redirect( admin_url('themes.php?activated=true') );
		exit;
	} elseif ( 'delete' == $_GET['action'] ) {
		check_admin_referer('delete-theme_' . $_GET['stylesheet']);
		$theme = wp_get_theme( $_GET['stylesheet'] );

		if ( ! current_user_can( 'delete_themes' ) ) {
			wp_die(
				'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
				'<p>' . __( 'You are not allowed to delete this item.' ) . '</p>',
				403
			);
		}

		if ( ! $theme->exists() ) {
			wp_die(
				'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
				'<p>' . __( 'The requested theme does not exist.' ) . '</p>',
				403
			);
		}

		$active = wp_get_theme();
		if ( $active->get( 'Template' ) == $_GET['stylesheet'] ) {
			wp_redirect( admin_url( 'themes.php?delete-active-child=true' ) );
		} else {
			delete_theme( $_GET['stylesheet'] );
			wp_redirect( admin_url( 'themes.php?deleted=true' ) );
		}
		exit;
	}
}

// Wrong plugin path
// wp_enqueue_script( 'script_handle', plugin_dir_url( __FILE__ ) . 'script.js', array( 'jquery', 'wp-util' ), '1.0', true );

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


if ( current_user_can( 'switch_themes' ) ) {
	$themes = wp_prepare_themes_for_js();
} else {
	$themes = wp_prepare_themes_for_js( array( wp_get_theme() ) );
}

require_once( ABSPATH . 'site-admin/admin-header.php' );
wp_print_scripts( array( 'wp-util' ) );
?>

<div class="wrap">
<div class="bg">
<center>
	<h1><?php echo '<span class="dashicons-before sme-dash-header dashicons-admin-appearance"></span> &nbsp; ';esc_html_e( 'Themes' ); ?>
		<span class="title-count themes-count"><?php echo count( $themes ); ?></span>
	</h1>
</center>

<form id="theme-filter" method="post">

<div class="row">
	<div class="col-sm-9"><div class="sp-search">
		<div class="search-box">
			<input type="search" name="search" class="search-input" value="<?php echo optREQ('q'); ?>" placeholder="<?php echo __('Search themes by name, category or tags e.g. pizza, portfolio, business, etc');?>" />
			<button onclick="return submit_search();" class="button" id="search-submit-sp" type="submit"></button>
			<div id="suggestion_list" class="suggestion_list"></div>
		</div>	
	</div></div>
	<div class="col-sm-3">
	
		<div class="pavigation-menu">
		<div class="pagination-ui float-right">
	<?php
	
	// Filter the themes as per category selected
	$category = optGET('category');
	$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('themes.php').'" data-page="1" title="First" class="page-link" >&laquo;</a></li><li class="page-item"><a href="'.admin_url( 'themes.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( 'themes.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('themes.php?'.$pagedurl.$next).'" data-page="'.$next.'" title="Next" class="page-link" >&gt;</a></li><li><a href="'.admin_url('themes.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 
if ( ! validate_current_theme() || isset( $_GET['broken'] ) ) : ?>
<div id="message1" class="updated notice is-dismissible"><p><?php _e('The active theme is broken. Reverting to the default theme.'); ?></p></div>
<?php elseif ( 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 id="category-list" class="category_list">
<center>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<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' : '').'" href="'.admin_url('themes.php').'" name="all">'.__('All').'</a></li>';
	
$cat_count = 0;
$morediv = '';
foreach($sp_category as $slug => $cat){
	
	$cat_lang_slug = 'ThemeCategory_'.$slug;
	$cat_name = __($cat['en']);
	
	if($cat_count < 11){
		echo '<li id="category_list_'.$slug.'" class="nav-item"><a class="'.$slug.' nav-link category-button'.(!empty($category) && $category == $slug ? ' active' : '').'" href="'.admin_url('themes.php?category='.$slug).'" name="'.$slug.'">'.$cat_name.'</a></li>';
		
	}else{
		$morediv .= '<a id="category_list_'.$slug.'" class="'.$slug.' dropdown-item category-li'.(!empty($category) && $category == $slug ? ' active' : '').'"  href="'.admin_url('themes.php?category='.$slug).'" name="'.$slug.'">'.$cat_name.'</a>';
	}
	$cat_count++;
}

echo '
	<li class="nav-item dropdown">
		<a class="nav-link dropdown-toggle" href="#" id="theme_navbar_dropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'.__('More').'</a>
		<div class="dropdown-menu" aria-labelledby="theme_navbar_dropdown">
		'.$morediv.'
		</div>
	</li>
</ul>
</nav>
</center>
</div>
</br>

<div class="theme-browser">
	<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;
}

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(isset($theme['type']) && $theme['type'] > $sitepad['features']['themes']){
		$needs_premium = 1;
	}
	
?>

<div class="theme<?php if ( $theme['active'] ) echo ' active'; ?>" tabindex="0">
<?php if(!empty($needs_premium)){
	echo '<div class="premium_themes">'.$sitepad['theme_levels'][$theme['type']].'</div>';
} ?>
<div id="<?php echo $theme['id']; ?>" class="themes_details" onclick="smtheme_details(this.id);">
	<?php if ( ! empty( $theme['screenshot'][0] ) ) { ?>
		<div class="theme-screenshot" >
			<img src="<?php echo $theme['screenshot'][0]; ?>" alt="" />
		</div>
	<?php } else { ?>
		<div class="theme-screenshot blank"></div>
	<?php } ?>
	<span class="more-theme-details"  ><?php _e( 'Theme Details' ); ?></span>
	<?php if ( $theme['active'] ) { ?>
		<h2 class="theme-name" id="<?php echo $aria_name; ?>">
			<?php
			/* translators: %s: theme name */
			printf( __( '<span>Active:</span> %s' ), $theme['name'] );
			?>
		</h2>
	<?php } else { ?>
		<h2 class="theme-name" id="<?php echo $aria_name; ?>"><?php echo $theme['name']; ?></h2>
	<?php } ?>
</div>
	<div class="theme-actions display_button_yes" id="theme_action">
	<?php if( !$theme['active'] ){ 
	
	if(!empty($needs_premium)){ ?>
		<a class="button button-secondary activate" href="<?php echo admin_url('plans.php'); ?>"><?php _e( 'View Plans' ); ?></a>
	<?php }else{ ?>
		<a class="button button-secondary activate" onclick="download_img_modal(this, event);" href="<?php echo $theme['actions']['activate']; ?>"><?php _e( 'Activate' ); ?></a>
		
	<?php }
	} ?>
	</div>
	
</div>

<?php endforeach; ?>
	<br class="clear" />
	</div>
</div>
<div class="theme-overlay"></div>
<div class="modal" tabindex="-1" role="dialog" id="sitepad-download-img-modal" style="z-index:99999;">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title"><?php _e('Image Copyright'); ?></h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
				<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<p><?php _e('We try our best to use images that are free from legal perspectives. However, we do not take any responsibility for the same. Do you want to use the demo images with this theme ?'); ?></p>
				<p><?php _e('If you click <b>Yes</b>, then the images will be downloaded from their respective sources. If you click <b>No</b>, then we will use placeholder images which are distributed with this theme and can be replaced easily.'); ?></p>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-primary sitepad-download-image"><?php _e('Yes'); ?></button>
				<button type="button" class="btn btn-secondary sitepad-download-image-no"><?php _e('No'); ?></button>
			</div>
		</div>
	</div>
</div>
<script>
var data_details = <?php echo json_encode($themes, JSON_PRETTY_PRINT); ?>;
var sp_category = <?php echo json_encode($sp_category, JSON_PRETTY_PRINT); ?>;

function smtheme_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]){
				data.previous = data_details[cur-1].id;
			}
			if(data_details[cur+1]){
				data.next = data_details[cur+1].id;
			}
			var smtemplate = wp.template('themes-details-wrap');
			sm_tmpl(data);
			function sm_tmpl( data ){
				$themes = jQuery(".theme-overlay").css('display','block');;
				$themes.html( smtemplate(data));
			}
		}
	}
}

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 = "<?php echo admin_url('themes.php'); ?>?q="+encodeURI(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">';
	if(!jQuery.isEmptyObject(data)){
		for(i in data){
			txt += '<li onClick="smtheme_details(\''+data[i]+'\');" style="cursor:pointer;" value='+data[i]+'>'+arr[i]+'</li>';
		}
	}else{
		txt += '<a class="inliner" href="javascript:void(0);"><li value="no-suggestion">No themes found with this search criteria</li></a>';
	}
	txt += '</ul>';
	var search_width = jQuery('.search-input').outerWidth();
	document.getElementById("suggestion_list").innerHTML=txt;
	document.getElementById("suggestion_list").style.display="block";
	jQuery("#suggestion_list").css({'min-width' : search_width, 'max-width' : search_width });
}

function download_img_modal(ele, e){
	e.preventDefault();
	
	var href = jQuery(ele).attr("href");
	var modal = jQuery("#sitepad-download-img-modal");
	modal.modal("show");
	
	modal.find(".sitepad-download-image").unbind("click");
	modal.find(".sitepad-download-image").on("click", function(){
		window.location.href = href+'&download_imgs=1';
		modal.modal("hide");
	});
	
	modal.find(".sitepad-download-image-no").unbind("click");
	modal.find(".sitepad-download-image-no").on("click", function(){
		window.location.href = href;
		modal.modal("hide");
	});
}

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

<script type="text/template" id="tmpl-themes-details-wrap">
<div class="theme-backdrop"></div>
<div class="theme-wrap" >
		<div class="theme-header">
			<button class="left dashicons dashicons-no" onclick="smtheme_details('{{{ data.previous }}}');"><span class="screen-reader-text"><?php _e( 'Show previous theme' ); ?></span></button>
			<button class="right dashicons dashicons-no" onclick="smtheme_details('{{{ data.next }}}');"><span class="screen-reader-text"><?php _e( 'Show next theme' ); ?></span></button>
			<button class="close dashicons dashicons-no" onclick="close_smdetails();"><span class="screen-reader-text"><?php _e( 'Close details dialog' ); ?></span></button>
		</div>
		<div class="theme-about">
			<# if ( !data.active && !data.actions.activate ) { #>
				<div id="message" class="error "><center><p>This theme is available only in the Premium package. <a href="<?php echo admin_url('plans.php'); ?>">Click here to view premium plans</a>.</p></center></div>
			<# } #>
			<div class="theme-screenshots">
			<# if ( data.screenshot ) { #>
				<div class="screenshot"><img src="{{ data.screenshot }}" alt="" id="data_screenshot"/></div>
			<# } else { #>
				<div class="screenshot blank"></div>
			<# } #>
			</div>

			<div class="theme-info">
				<h2 class="theme-name">{{{ data.name }}}<span class="theme-version"><?php printf( __( 'Version: %s' ), '{{ data.version }}' ); ?></span>
				<# if ( ! data.active && data.actions.activate ) { #>
					<a href="{{{ data.actions.activate }}}" class="button button-secondary activate" onclick="download_img_modal(this, event);"><?php _e( 'Activate' ); ?></a>
				<# } #>
				<# if ( !data.active && !data.actions.activate ) { #>
					<a href="<?php echo admin_url('plans.php'); ?>" class="button button-secondary activate premium"><?php _e( 'View Plans' ); ?></a>
				<# } #>
				<?php if(empty($SESS['no_demos'])){ ?>
				<# if ( data.demo ) { #>
					<a class="button button-primary" href="<?php echo BRAND_SM_DEMOS; ?>{{{ data.demo }}}/" target="_blank" style="text-decoration:none; color:#FFF;"><?php _e( 'Demo' ); ?></a>
				<# } #>
				<?php } ?>
				</h2>
				<# if ( data.active ) { #>
					<span class="current-label"><?php _e( 'Current Theme' ); ?></span>
				<# } #>
				
				<p class="theme-description">{{{ data.description }}}</p>

				<# if ( data.parent ) { #>
					<p class="parent-theme"><?php printf( __( 'This is a child theme of %s.' ), '<strong>{{{ data.parent }}}</strong>' ); ?></p>
				<# } #>
				
				<# if ( data.category ) { #>
					<p class="theme-category"><span><?php _e( 'Category:' ); ?></span> {{{ data.category }}}</p>
				<# } #>
				<# if ( data.tags ) { #>
					<p class="theme-tags"><span><?php _e( 'Tags:' ); ?></span> {{{ data.tags }}}</p>
				<# } #>
				
			</div>
		</div>

		<div class="theme-actions">
			<div class="active-theme">
				<a href="{{{ data.actions.customize }}}" class="button button-primary customize load-customize hide-if-no-customize"><?php _e( 'Customize' ); ?></a>
				<?php echo implode( ' ', $current_theme_actions ); ?>
			</div>
			<div class="inactive-theme">
				
				<a href="{{{ data.actions.customize }}}" class="button button-primary load-customize hide-if-no-customize"><?php _e( 'Live Preview' ); ?></a>
			</div>

			<# if ( ! data.active && data.actions['delete'] ) { #>
				<a href="{{{ data.actions['delete'] }}}" class="button button-secondary delete-theme"><?php _e( 'Delete' ); ?></a>
			<# } #>
		</div>
</div>
</div>
</script>

<?php

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