<?php

// We need the ABSPATH
if (!defined('ABSPATH')) exit;

// Enqueue our JS for various stuff
add_action('pagelayer_custom_editor_enqueue', 'sitepad_pagelayer_editor_enqueue');
function sitepad_pagelayer_editor_enqueue(){
	
	wp_register_script('sitepad-editor', SITEPAD_JS.'/givejs.php?give=sitepad-editor.js,html2canvas.min.js', array('jquery'), SITEPAD_VERSION);
	wp_enqueue_script('sitepad-editor');
	
}

// Handle export of files
add_filter('pagelayer_right_bar_promos', 'sitepad_pagelayer_right_bar_promos', 10, 1);
add_filter('pagelayer_review_link', 'sitepad_pagelayer_right_bar_promos', 10, 1);
function sitepad_pagelayer_right_bar_promos($val){
	return false;
}

// Enqueue our JS for various stuff
add_action('pagelayer_live_body_head', 'sitepad_live_body_head');
function sitepad_live_body_head(){
	
	echo '
<style>
.sitepad-top-bar-left>div{
display: inline-block;
font-size: 13px;
color: #fff;
}

.sitepad-screen-mode-fix{
bottom: auto !important;
top: 100%;
left: 10%;
}

.pagelayer-bottombar-holder{
padding: 9px;
background-color: transparent;
}

.pagelayer-topbar-holder{
background-color: #455366;
}

.pli-wordpress:before,
i[class*="pagelayer-pl_wp_"]:before{
content: "\e921";
}

.sitepad-top-bar-options{
position:relative;	
}

.sitepad-seo-option{
color:#fff;
cursor:pointer;	
}

#sitepad-seo-option-div{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: #000000a6;
overflow:auto;
}

.sitepad-seo-option-wrapper{
width: 60%;
margin: auto;
top: 5%;
position: relative;
background: #fff;
box-shadow: 0px 0px 7px 0px #fff;
border-radius: 5px;
}

.sitepad_meta_heading,
.sitepad-meta-footer,
.sitepad_meta_data{
padding:10px 20px;
position:relative;	
}

.sitepad_meta_heading .pli{
position: absolute;
cursor: pointer;
right: 20px;
top: 20px;
}

.sitepad_meta_data table{
width: 90%;
margin: auto;
border-collapse: separate;
border-spacing: 10px;
border-color: gray;
}

.sitepad_meta_data table input,
.sitepad_meta_data table textarea{
width:100%;
border: 1px solid #ddd;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.07);
box-shadow: inset 0 1px 2px rgba(0,0,0,.07);
background-color: #fff;
color: #32373c;
border-radius: 4px;
padding: 6px 12px;
resize: vertical;
}

.sitepad-meta-footer button{
cursor: pointer;
border-radius: 2px;
padding: 4px 8px;
margin: auto 5px;
outline: none;
}

.sitepad-success-btn{
border: #398439 1px solid;
color: #fff;
background: #449d44;
}

.sitepad-danger-btn{
border: #ef4d4d 1px solid;
color: #fff;
background: #ef4d4d;
}

.sitepad-default-btn{
border: #636363  1px solid;
color: #fff;
background: #636363;
}

.sitepad-close-right{
float: right;
cursor: pointer;
}
</style>';
	
}

add_action('pagelayer_editor_wp_head' , 'sitepad_pagelayer_editor_wp_head', 0);
function sitepad_pagelayer_editor_wp_head(){

	echo '
<script>
sitepad_ajax_url = "'.admin_url( 'admin-ajax.php?' ).'&";
sitepad_ajax_nonce = "'.wp_create_nonce('sitepad_ajax').'";
sitepad_brand_sm = "'.BRAND_SM.'";
</script>';

}

// Live Variables
add_action('pagelayer_iframe_top_bar', 'sitepad_iframe_top_bar');
function sitepad_iframe_top_bar(){
	
	global $post, $l;
	
	$blog_id = get_current_blog_id();
	$dest_url = rtrim(get_user_meta(1, $blog_id.'_sitepad_domain', 1) . get_user_meta(1, $blog_id.'_sitepad_path', 1), '/');
	$download_url = admin_url('publish.php?download=now&siteid='.$blog_id);
	
	echo '<table width="100%" cellpadding="0" cellspacing="0">
<tr>
	<td class="sitepad-top-bar-left">';
	
	if($post->post_type == 'pagelayer-template' || $post->post_type == 'page'){
		
		echo '
		<div class="sitepad-cur-page" style="padding: 0px 10px;">
'.($post->post_type == 'page' ? __('Pages') : __('Templates')).' : 
			<select style="margin-top:0px; min-width:110px;" onchange="pagelayer_iframe_cw.sitepad_selectPage(this)">
				<option value="'.($post->post_type == 'page' ? admin_url("post-new.php?post_type=page") : esc_url(admin_url('admin.php?page=pagelayer_template_wizard'))).'" style="border-bottom: 2px dotted #000;">'.__('Create New').'</option>';
				
		$post_ids = get_posts(array(
			'posts_per_page'=> -1,
			'fields'        => 'ids', // Only get post IDs
			'post_type'   => $post->post_type,
			'post_status' => array('draft', 'publish')
		));
			
		foreach($post_ids as $page){
			$can_edit_post = current_user_can('edit_post', $page);
			if($can_edit_post && get_option('page_for_posts') != $page){
				echo '<option value="'.pagelayer_livelink($page).'" '.(($post->ID == $page) ? 'selected' : '').'>'.get_the_title($page).'</option>';
			}
		}
	
		echo '
			</select>
		</div>';
		
	}
	
	// Get Meta Data
	$values = wp_unslash( get_post_meta($post->ID, 'sitepad_meta_tags', true) );
		
	echo '
	</td>
	<td class="sitepad-top-bar-right" align="right"></td>
	<td class="sitepad-top-bar-options" width="30px" style="position:relative;">
		<span data-tlite="SEO Settings"><i class="sitepad-seo-option pli pli-menu" title="SEO Settings"></i></span>
		<div id="sitepad-seo-option-div" style="display: none;">
			<div class="sitepad-seo-option-wrapper">
				<center class="sitepad_meta_heading">
					<h2 style="margin:0px">'. __('MetaTags') .' </h2><i class="meta-tags-close pli pli-cross"></i>
				</center>
				<hr />
				<div class="sitepad_meta_data">
					<form id="sitepad_meta_form" name="sitepad_meta_form">
						<table>
							<tr>
							<td colspan="2" style="align:middle;">
								<b style="color:#BF4F4F">'. __('Note: If Meta Data is not found for a particular Page / Post, the <a href="'.admin_url('seo.php').'" target="_blank"> Global Meta Data</a> will be used.').'</b>
							</td>
							</tr>
							<tr>
							<td colspan="2" style="align:middle;">
								<p>'. __('There are some pre defined variables:- $site_title, $page_title, $post_type, $author, $email.').'</p>
							</td>
							</tr>
							<tr>
							<td style="text-align: left" width="25%"> '. __('Site Title').' : </td>
							<td width="70%">
								<input type="text" name="site_title" id="site_title" value="'.(!empty($values['site_title']) ? $values['site_title'] : '' ).'" style="width:100%;" />
							</td>
							</tr>
							<tr>		
							<td style="text-align: left" width="25%"> '. __('Author').' : </td>
							<td width="70%">
								<input type="text" name="meta_author" id="meta_author" value="'.(!empty($values['meta_author']) ? $values['meta_author'] : '' ).'"  style="width:100%;" />
							</td>
							</tr>
							<tr>
							<td style="text-align: left" width="25%"> '. __('Contact').' : </td>
							<td width="70%">
								<input type="email" name="meta_contact" id="meta_contact" value="'.(!empty($values['meta_contact']) ? $values['meta_contact'] : '' ).'" style="width:100%;"  />
							</td>
							</tr>
							<tr>
							<td style="text-align: left" width="25%"> '. __('Copyright').' : </td>
							<td width="70%">
								<input type="text" name="meta_copyright" id="meta_copyright" value="'.(!empty($values['meta_copyright']) ? $values['meta_copyright'] : '' ).'" style="width:100%;"  />
							</td>
							</tr>
							<tr>
							<td style="text-align: left" width="25%"> '. __('Description').' : </td>
							<td width="70%">
								<textarea rows="3" cols="50" name="meta_description" id="meta_description" >'.(!empty($values['meta_description']) ? $values['meta_description'] : '' ).'</textarea>
							</td>
							</tr>
							<tr>
							<td style="text-align: left" width="25%"> '. __('Keywords').' : </td>
							<td width="70%">
								<textarea rows="3" cols="50" name="meta_keys" id="meta_keys" >'.(!empty($values['meta_keys']) ? $values['meta_keys'] : '' ).'</textarea>
							</td>
							</tr>
						</table>
					</form>
				</div>	
				<hr />
				<div class="sitepad-meta-footer">
					<button class="sitepad-success-btn meta-tags-submit">'. __('Save Meta').'</button>
					<button class="sitepad-danger-btn meta-tags-clear">'. __('Clear Meta').'</button>
					<button class="sitepad-default-btn meta-tags-close sitepad-close-right">'. __('Close').'</button>
				</div>
			</div>
		</div>
	</td>
</tr>
</table>';

}

// Handle export of files
add_filter('pagelayer_save_content', 'sitepad_pagelayer_save_content', 10, 1);
function sitepad_pagelayer_save_content($post){
	
	global $sitepad;
	
	// Replace Upload URLs which are as per the 
	$post['post_content'] = preg_replace('/:\/\/('.preg_quote($sitepad['serving_upload_url'], '/').')/is', '://'.$sitepad['uploads_domain'], $post['post_content']);
	
	// Replace URLs which are as per the 
	$post['post_content'] = preg_replace('/:\/\/('.preg_quote($sitepad['serving_url'], '/').')/is', '://'.$sitepad['domain'], $post['post_content']);
	
	return $post;
}

// When a page has been exported
add_action('pagelayer_page_exported', 'sitepad_pagelayer_page_exported', 10, 2);
function sitepad_pagelayer_page_exported($post, $theme_dir){
	
	global $sitepad;
	
	$screenshots = $theme_dir.'/screenshots';
	
	// Make a folder if missing
	if(!is_dir($screenshots)){
		mkdir($screenshots);
	}

	// Check if there is a screenshot file
	if(file_exists($sitepad['screenshots_path'].'/'.$post->post_name.'.jpg')){
		copy($sitepad['screenshots_path'].'/'.$post->post_name.'.jpg', $screenshots.'/'.$post->post_name.'.jpg');
	}
	
}

function clean_url_slash($url){
	$url = str_replace('//', '/', $url);
	$url = str_replace('//', '/', $url);
	$url = str_replace('//', '/', $url);
	$url = str_replace('http:/', 'http://', $url);
	$url = str_replace('https:/', 'https://', $url);
	return $url;
}

// Handle Pagelayer Image URLs for TMP urls
add_filter('pagelayer_image', 'sitepad_pagelayer_imager_url', 10, 1);
add_filter('pagelayer_attachment', 'sitepad_pagelayer_imager_url', 10, 1);
function sitepad_pagelayer_imager_url($ret){
	
	global $sitepad;
	
	foreach($ret as $k => $v){
		
		if(preg_match('/(http(s?):\/\/'.preg_quote($sitepad['domain'], '/').')/is', $ret[$k])){
			$ret[$k] = preg_replace('/(http(s?):\/\/'.preg_quote($sitepad['domain'], '/').')/is', $sitepad['url'], $ret[$k]);
		}
		
		if(preg_match('/(http(s?):\/\/'.preg_quote($sitepad['uploads_domain'], '/').')/is', $ret[$k])){
			$ret[$k] = preg_replace('/(http(s?):\/\/'.preg_quote($sitepad['uploads_domain'], '/').')/is', $sitepad['upload_url'], $ret[$k]);
		}
	}
	
	return $ret;
}

// Handle get post content with replaced URLs
add_filter('pagelayer_sanitize_do_shortcode', 'sitepad_pagelayer_replace_url', 10, 1);
function sitepad_pagelayer_replace_url($value){
	
	global $sitepad;

	// Replace Upload URLs which are as per the
	if(preg_match('/('.preg_quote($sitepad['uploads_domain'], '/').')/is', $value)){
		$value = preg_replace('/('.preg_quote($sitepad['uploads_domain'], '/').')/is', $sitepad['serving_upload_url'], $value);
	}
	
	// Replace URLs which are as per the 
	if(preg_match('/('.preg_quote($sitepad['domain'], '/').')/is', $value)){
		$value = preg_replace('/('.preg_quote($sitepad['domain'], '/').')/is', $sitepad['serving_url'], $value);
	}
	
	return $value;
}

// Handle export of sitepad.local URLs as well
add_filter('pagelayer_export_content', 'sitepad_pagelayer_export_content', 5, 1);
function sitepad_pagelayer_export_content($content){
	
	global $sitepad;
	
	// Theme URL correction code for sitepad.local
	$theme_url = preg_replace('/http(s?):\/\//is', '', get_stylesheet_directory_uri());
	$theme_url = str_replace($sitepad['serving_url'], $sitepad['domain'], $theme_url);
	
	$content = pagelayer_export_theme_links($content, $theme_url);
	
	return $content;
}