<?php

class core_coupons extends white_label_themes {

 
function storestop($c){ 

// TERM DATA
$term = get_term_by('slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );   

ob_start(); 

?>

<div class="well storetitle">
    <div class="row ">
        <div class="col-md-4">
    	
        <div class="thumbnail">
        
        <?php
				
		if(isset($GLOBALS['CORE_THEME']['category_website_'.$term->term_id]) && strlen($GLOBALS['CORE_THEME']['category_website_'.$term->term_id]) > 1){	?>
        
        	<?php echo do_shortcode('[SCREENSHOT url="'.$GLOBALS['CORE_THEME']['category_website_'.$term->term_id].'" alt="'.$term->name.'"]'); ?>
            
        <?php }elseif(isset($GLOBALS['CORE_THEME']['category_icon_'.$term->term_id]) && strlen($GLOBALS['CORE_THEME']['category_icon_'.$term->term_id]) > 1){
		
		?>
       
     	 <img src="<?php echo $GLOBALS['CORE_THEME']['category_icon_'.$term->term_id]; ?>" alt="<?php echo $term->name; ?>" class="img-responsive" />
           
        
        <?php }else{ ?>
        
            <div class="frame">
            <img src="<?php echo get_template_directory_uri().'/templates/'.get_option('wlt_base_theme').'/img/screen.jpg'; ?>" alt="<?php echo $term->name; ?>" />
            </div>
        
        <?php } ?>       
        </div>
        
        </div>
        <div class="col-md-8">
        
        <?php echo $c; ?>
        
        </div>
    </div>
</div>

<?php
return ob_get_clean(); 
}

function wlt_shortcode_coupon_data(){ global $post, $CORE;

// GET TEXT
$text = get_post_meta($post->ID, 'coupon_txt', true);
if($text == ""){ 

	// TRY TO AUTO GENERATE TXT FROM CONTENT
	preg_match_all("/[0-9]+%/", $post->post_title, $percentage);
	if(isset($percentage[0][0]) && $percentage[0][0] != ""){	 
	$text = $percentage[0][0]." Off";
	}
	
	if($text == ""){ 
	
		preg_match_all("/[$-£]+[0-9]/", htmlentities($post->post_title), $percentage);			 
		if(isset($percentage[0][0]) && $percentage[0][0] != "" ){	 
		$text = $percentage[0][0]." Off"; 
		}
	}
	
	if($text == ""){ 
		if (strpos(strtolower($post->post_title), "free upgrade") !== false) {	
			$text = "free upgrade";
		}	
	}
	
	if($text == ""){ 
		$text = "discount";
	}
 
 }	

// GET TYPE
$type = get_post_meta($post->ID, 'coupon_type', true);
switch($type){
	case "2": { $txt1 = $CORE->_e(array('coupons','10')); } break;
	case "3": { $txt1 = $CORE->_e(array('coupons','11')); } break;
	default: { $txt1 = $CORE->_e(array('coupons','9')); }
}

// POUND SYMBOL ISSUE
$text = str_replace("&Acirc;","",$text);
$text = str_replace("&pound;",'<i class="fa fa-gbp" style="font-size: 90%;    margin-right: 4px;"></i>',$text);



ob_start();
?>

<div class="codedata clearfix text-center">
    <div class="cwrap">
    
    <div class="txt"><?php echo $text; ?></div>
 
    <div class="type"><?php echo $txt1; ?></div>

    </div>
   
</div>
<?php
return ob_get_clean(); 
}
	function __construct(){ global $wpdb;	
  	
		if(is_admin()){
 
			add_action('hook_admin_1_pagesetup', array($this, '_hook_admin_1_pagesetup'  ) ); 
				
			add_action('hook_admin_2_tags_search', array($this,'wlt_coupon_new_tags') );	
		  
		}
		
		// MOBILE FUNCTIONS
		add_action('hook_admin_1_tab1_mobile_homelist', array($this, 'hook_admin_1_tab1_mobile_homelist') );
		add_action('hook_mobile_header', array($this, 'mobile_header' ) );
		add_action('hook_mobile_footer', array($this, 'mobile_footer' ) );
		add_action('hook_mobile_content_output', array($this, 'mobilesearchcontent' ), 1 );
		add_action('hook_mobile_content_homepage', array($this, 'hook_mobile_content_homepage' ) );
 	
		// HOOK ALL CUSTOM QUERIES TO REMOVE EXPIIRED COUPONS FROM DISPLAY
	 	add_action('hook_custom_queries',  array($this, '_hook_custom_query' ) );
	 
		// ADD HOOK INTO CUSTOM SEARCH FOR STORE ID
		add_action('hook_wlt_core_search', array($this, '_customsearch' ));
		// NEW TAXONOMIES
		if(strlen(get_option('premiumpress_storeslug')) > 1){ $store_slug_name = get_option('premiumpress_storeslug'); }else{ $store_slug_name = 'store'; }
		register_taxonomy( 'store', THEME_TAXONOMY.'_type', array( 'hierarchical' => true, 'labels' => array('name' => 'Stores') , 'query_var' => true, 'rewrite' => true, 'rewrite' => array('slug' => $store_slug_name) ) );	 
		
		// FOOTER JAVASCRIPT
		add_action('wp_footer', array($this, '_new_js' ));
		
		// HOOK SUBMISSION PAGE AND ADD IN CORE FIELDS
		if(get_option('coupon_defaults') != '1'){	 
	 	add_action('hook_add_fieldlist',  array($this, '_hook_customfields' ) );
		add_action('hook_custom_fields_filter', array($this, '_remove_oldfields') );
		add_action('hook_fieldlist_0', array($this, '_blankfields' ) );
		}
		// ADD COUPON IMAGE FALLBACK 
		add_action('hook_fallback_image_display', array($this, 'wlt_coupon_fallback_image_tostore'  ));
		// REGISTER COUPON WIDGETS
		register_widget( 'core_widgets_stores' );
		 
		// COUPON ACTIVATED SHORTCODES	
		add_shortcode( 'STORES', array($this,'wlt_shortcode_stores') );
		add_shortcode( 'STORE', array($this,'wlt_shortcode_store') );
 
		add_shortcode( 'COUPON_START', array($this,'wlt_shortcode_coupon_starts') );
		add_shortcode( 'COUPON_END', array($this,'wlt_shortcode_coupon_ends') );
		add_shortcode( 'CBUTTON', array($this,'wlt_shortcode_coupon_button') );
 		add_shortcode( 'COUPON', array($this,'wlt_shortcode_coupon_button') );
 		add_shortcode( 'COUPON_TITLE', array($this,'wlt_shortcode_coupon_title') );	
		add_shortcode( 'COUPON_USED', array($this,'wlt_shortcode_coupon_used') );		
		add_shortcode( 'COUPONDATA', array($this,'wlt_shortcode_coupon_data') );
		
		// CUSTOM STORE SLUG
		add_action('admin_footer', array($this, 'custom_permalinks') );
		
		// CHECK IF ITS EXPIRED
		add_action('hook_content_listing_class', array($this, '_hook_content_listing_class') );
		
		// ADD ON  PAGE LINK
		add_action('hook_admin_1_tab1_subtab2_pagelist', array($this,'_updatepagelist' ));
		
		// TAXONOMY PAGE STORE TITLE
		add_action('hook_taxonomy_content_top', array($this, 'storestop' ) );
 
	}
	
	function wlt_shortcode_coupon_used(){ global $post, $CORE;
	
	$lastused = get_post_meta($post->ID,'lastused',true);
	if($lastused == ""){ return; }
	
	$timesince = $this->TimeDiff($lastused);	 
	if(strlen($timesince['date']) < 5){ return; } 
	
	ob_start(); 
	?>
    <span class="wlt_shortcode_coupon_used"> <?php echo str_replace("%a",$timesince['date'],$CORE->_e(array('coupons','47')) );; ?> </span>
    <?php
	
	return ob_get_clean();
	}

/* =============================================================================
	  MOBILE ADJUSTMENTS
	========================================================================== */ 
	
	function mobile_header(){ ?>
    <style>
    .home h4 { margin:0px; padding:0px; margin-left:-10px; margin-right:-10px; line-height:50px; border-top:1px solid #ccc; margin-top:30px; padding-left:20px; background:#fff; }
    .storelist { background:#fff; margin-left:-10px; margin-right:-10px; margin-bottom:-20px; border-top:1px solid #ddd;  }
    .storelist li { border-bottom:1px solid #ddd; padding-top:5px; padding-bottom:5px; font-size:14px; line-height:40px; }
    .storelist i { margin-top:12px; color:#ddd;   }
    .storelist .col-xs-2 { padding:0px; }
    .storelist .col-xs-2 img { margin-left:2px; margin-top:10px; }
	.wlt_thumbs_style1 { margin:0px !important; padding:0px;  }
	.wlt_thumbs_style1 .btn { padding:0px; margin-right:10px; background:none; color:#999; font-weight:bold; font-size:12px; }
	.wlt_thumbs_style1 .btn i { color:#999; font-size:12px; }
	.searchblock .wlt_shortcode_code:before { content: "\e032"; padding-right:5px; font-family: 'Glyphicons Halflings'; font-size:7px; }
	</style>
    <?php }
	function mobile_footer(){ } 	
	function mobilesearchcontent(){ $GLOBALS['CUSTOMMOBILECONTENT'] = true; global $post; ?>
	<div style="padding:15px;">
    
   
    
	<h2 style="font-weight:bold;"><a href="<?php echo home_url(); ?>/out/<?php echo $post->ID; ?>/link/">[TITLE-NOLINK]</a></h2>
    [code]
	[EXCERPT size=60]
	</div>
	<div style="background:#eee; height:30px; padding:5px; font-size:11px; text-transform:uppercase; color:#999; font-weight:bold; ">
	<div class="row">
	 
    <div class="col-md-4 col-xs-5" style="font-size:10px;">[RATING style=2] </div> 
	<div class="col-md-8 col-xs-7 text-right" style="font-size:10px;">[COUPON_END small=1] </div> 
	</div>     
	</div>
	<?php }
	
	function hook_mobile_content_homepage($c){  global $wpdb, $CORE;	
	 
	if($GLOBALS['CORE_THEME']['mobileweb_homesetup'] != '4'){  return $c; }	
	ob_start();
	?>
    
    <a href="<?php echo home_url(); ?>/" id="logo1"><?php echo $GLOBALS['CORE_THEME']['mobileweb_logo']; ?></a>
    <div class="clearfix"></div>
    
    <h4><?php echo $CORE->_e(array('coupons','38')); ?></h4>
    <div class="storelist">
    <ul>
    <?php 
    
    $args = array(
                  'taxonomy'     => 'store',
                  'orderby'      => 'count',
                  'order'		=> 'desc',
                  'show_count'   => 0,
                  'pad_counts'   => 1,
                  'hierarchical' => 0,
                  'title_li'     => '',
                  'hide_empty'   => 0,
                 
    );
    $categories = get_categories($args);  $nc = 1;		
    foreach ($categories as $category) {
    
     
    // hide none parents
    if($category->parent != 0){ continue; } 
             
        $LINK 	= get_term_link($category->slug, 'store');
        $NAME 	= $category->name;			 
                
        if(isset($category->term_id) && isset($GLOBALS['CORE_THEME']['category_icon_'.$category->term_id]) ){
        $IMG = $GLOBALS['CORE_THEME']['category_icon_'.$category->term_id];
        }
                
        if($IMG == ""){ $IMG = get_template_directory_uri()."/framework/img/demo/noimage.png"; }
        $DESC 	= $category->category_description;
         
    ?>
    <li>
    
        <a href="<?php echo $LINK; ?>" class="clearfix" style="position:relative"> 
            <div class="col-md-2 col-xs-2">
             <?php if(strlen($IMG) > 1){ ?><img src="<?php echo $IMG; ?>" alt="cat" class="img-responsive" /><?php } ?>
            </div>
            <div class="col-md-10 col-xs-10">
             <i class="glyphicon glyphicon-chevron-right pull-right"></i>
            <?php echo $NAME; ?> (<?php echo $category->count; ?>)
            </div>				 
        </a>
     
    </li>       
    <?php $i++; } ?>
    </ul>
    </div>
    <?php 
	
	return  ob_get_clean();
	}


	function hook_admin_1_tab1_mobile_homelist(){ global $CORE, $wpdb; $core_admin_values = get_option("core_admin_values"); 
	?>
	<option <?php selected( $core_admin_values['mobileweb_homesetup'], "4" );  ?> value="4"><?php echo $CORE->_e(array('coupons','41')); ?></option>
	<?php
	}
	

		
	// SHORTCODE 
	function wlt_shortcode_coupon_title(){ global $post, $CORE;
	
		// GET CURRENT PAGE LINK
		$currentlink = $CORE->format_webpath('');
				
		$string = "<a href='javascript:void(0);' class='ctitle".$post->ID."'>".$post->post_title."</a>";
	
		$string .= "<script>
						jQuery('.ctitle".$post->ID."').on( \"click\", function() {						
						window.location.href='".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/';	
						var win = window.open(  '". $currentlink ."couponid=".$post->ID."#itemid".$post->ID."',  '_blank' );						
						this.window.focus();
						
						});						
						</script>";
		return $string;
	}
	
	
 	// ADD NEW PAGE SELECTION FOR CHECKOUT IN THE ADMIN
	function _updatepagelist($c){
 
	$c['stores'] = array("name" => "Stores Page");
	return $c;
	}
  
	
	// ADD IN CORE FIELDS TO THE ADMIN
	function _blankfields($c){ global $CORE;
	
	$coupon_fields = array (
		"tab4" => array("tab" => true, "title" => "Coupon Theme Extras" ),
		
		"coupon_type" => array("label" => "Coupon Type", "values" => array("1" => "Website Coupon", "2" => "Printable Coupon",  "3" => "Deals &amp; Offers") ), 	 
		//"printable" => array("label" => "Printable", "values" =>array("0"=>"no", "1"=>"yes" ) ), 
		
		"code" => array("label" => "Coupon Code", ), 
		"coupon_txt" => array("label" => "Discount Text", ), 
		
		
		"link" => array("label" => "Affiliate Link", "desc" => "This is the link the user will be taken too."), 
		"start_date" => array("label" => "Coupon Start Date", "desc" => "Format: 2013-09-12 05:18:06", "dateitem" => true   ), 
		"expiry_date" => array("label" => "Coupon Expiry Date", "desc" => "Format: 2013-09-12 05:18:06", "dateitem" => true  ), 
		
		
	);
	 
	return array_merge($c,$coupon_fields);
	}
	function custom_permalinks(){ global $pagenow;
	
		if($pagenow == "options-permalink.php" ){ 
		
		
		$default_perm = get_option('premiumpress_storeslug');
		if($default_perm == ""){
		$default_perm = 'store';
		}
	  
			echo "<script> 
			jQuery(document).ready(function(){
				jQuery('table.permalink-structure').prepend( '<tr><th><label><input type=\"hidden\" name=\"submitted\" value=\"yes\">Coupon Store Slug</label></th><td> <input name=\"adminArray[premiumpress_storeslug]\" type=\"text\" value=\"".$default_perm."\" class=\"regular-text code\"><p><p>IMPORTANT. This option will let you change the slug display name from /store/ to your chosen value however doing so will change all of your existing store permalinks.</p></td></tr>' );
			});
			</script>";		
		
		}
	}
	function _remove_oldfields($c){
	if(!is_array($c)){ return $c; }
	
	$removeme = array('code','link','start_date','expiry_date');
	foreach($c as $k=>$v){
		if(in_array($v['key'],$removeme)){ unset($c[$k]); }	
	}
	
	return $c;
	}
	function _hook_customfields($c){ global $CORE;
	
		$o = 50;
		
		$c[$o]['title'] 	= $CORE->_e(array('coupons','8'));
		$c[$o]['name'] 		= "coupon_type";
		$c[$o]['type'] 		= "select";
		$c[$o]['class'] 	= "form-control";
		$c[$o]['listvalues'] 	= array("1" => $CORE->_e(array('coupons','9')), "2" => $CORE->_e(array('coupons','10')),  "3" => $CORE->_e(array('coupons','11')));
		$c[$o]['help'] 		= "<script>jQuery('#form_coupon_type').change(function(e) { if(jQuery('#form_coupon_type').val() == '2'){ jQuery('#form_printable').val('yes'); jQuery('#form-row-rapper-code').hide(); } else if(jQuery('#form_coupon_type').val() == '3'){ jQuery('#form-row-rapper-code').hide(); } else { jQuery('#form-row-rapper-code').show(); jQuery('#form_printable').val('no');  } }); </script> ";
		$o++;
		
		//$c[$o]['title'] 	= "";
		//$c[$o]['name'] 		= "printable";
		//$c[$o]['type'] 		= "hidden";
		//$c[$o]['values'] 	= "no";
		//$c[$o]['class'] 	= "form-control";
		//$o++;		
		
		$c[$o]['title'] 	= $CORE->_e(array('coupons','12'));
		$c[$o]['name'] 		= "code";
		$c[$o]['type'] 		= "text";
		$c[$o]['class'] 	= "form-control";
		$c[$o]['help'] 		= $CORE->_e(array('coupons','13'));
		$c[$o]['required'] 	= false;
		$o++;
		
		$c[$o]['title'] 	= $CORE->_e(array('coupons','14'));
		$c[$o]['name'] 		= "link";
		$c[$o]['type'] 		= "text";
		$c[$o]['class'] 	= "form-control";
		$c[$o]['help'] 		= $CORE->_e(array('coupons','15'));
		$c[$o]['defaultvalue'] 	= "http://";
		$o++;
		
		$c[$o]['title'] 	= $CORE->_e(array('coupons','16'));
		$c[$o]['name'] 		= "start_date";
		$c[$o]['type'] 		= "date";
		$c[$o]['class'] 	= "form-control";
 		 
		$o++;
		
		$c[$o]['title'] 	= $CORE->_e(array('coupons','17'));
		$c[$o]['name'] 		= "expiry_date";
		$c[$o]['type'] 		= "date";
		$c[$o]['class'] 	= "form-control";
 		
				
		return $c;
	}	
 
	// FOOTER JS FOR COUPON POP-UP
	function _new_js(){global $CORE; ?>
    
    <?php if($GLOBALS['CORE_THEME']['coupon_style'] == 3){ ?>
    <script src="<?php echo get_bloginfo('template_url'); ?>/templates/template_coupon_theme/js/jquery.zclip.js" type="text/javascript"></script>	 	
    <?php } ?>
    
    
    <?php if(isset($_GET['couponid']) && is_numeric($_GET['couponid']) ){ 
	
	$post_data = get_post($_GET['couponid']);
	
	// CHECK IT HAS A COUPON
	$has_code 		= get_post_meta($post_data->ID,"code",true);		
	if(trim($has_code) == ""){ $has_code = $CORE->_e(array('coupons','40')); } 
	
	// UPDATE LAST USED
	update_post_meta($post_data->ID,'lastused', date("Y-m-d H:i:s"));
	
	?>
    <style>
	
	.fa-envelope-o { font-size:80px; margin-right:20px; }
	
	@media (max-width: 480px) { 
	.fa-envelope-o { display:none;}
	.media-heading { font-size:14px; }	
	#wlt_popmodal .btn-lg { font-size:13px; }
	.clipbox { font-size:16px; }
	.btn-success { margin-top:-10px; }
	.btn-success span { font-size:12px; text-indent:-9999px; position:absolute; }
	.btn-success:before{ font-family: 'Glyphicons Halflings'; content: "\e015"; }
	.clipbox { margin-left:0px; }
	.clipbox:before { content: ""; }
	}
	</style>
    
<div class="modal fade" id="wlt_popmodal" >
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style=" background:#222; color:#fff;">
        <button type="button" class="close" style="opacity:1; margin-top: -8px;  background: #000;  padding: 10px;  color: #fff;" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title"><?php echo $post_data->post_title; ?></h4> 
      </div>
      <div class="modal-body text-center">
      
      <div style="font-size:21px; font-weight:300; "><?php echo $CORE->_e(array('coupons','42')); ?></div>
      
      <hr>
      
      <div class="clipbox text-left">
      
      <a href="<?php echo get_home_url()."/out/".$post_data->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/"; ?>" class="btn btn-success btn-lg pull-right"><span><?php echo $CORE->_e(array('coupons','43')); ?></span> </a>
      
      
      <?php echo $has_code; ?>
      
      
      </div>
      
      <hr>
      
      
      
      <div class="rc<?php echo $post_data->ID; ?>ty" style="display:none; font-size:30px;">Thank You!</div>
    
      <section id="rc<?php echo $post_data->ID; ?>">
      
      <div class="row">
      <div class="col-md-5 hidden-xs" style="line-height:50px;">
      
      <?php echo $CORE->_e(array('coupons','44')); ?>
      
      </div>     
      
      <div class="col-md-3 col-xs-6"> 
		
        <a href="javascript:void(0);" class="btn up btn-info btn-lg" onclick="WLTSaveUpRating('<?php echo str_replace("http://","",get_home_url()); ?>', '<?php echo $post_data->ID; ?>', 'up', 'core_ajax_callback');jQuery('#rc<?php echo $post_data->ID; ?>').hide();jQuery('.rc<?php echo $post_data->ID; ?>ty').show();"><?php echo $CORE->_e(array('coupons','45')); ?> </a>
	
    </div>
	
    <div class="col-md-3 col-xs-6">
				  
	<a href="javascript:void(0);" class="btn down btn-danger btn-lg" onclick="WLTSaveUpRating('<?php echo str_replace("http://","",get_home_url()); ?>', '<?php echo $post_data->ID; ?>', 'down', 'core_ajax_callback');jQuery('#rc<?php echo $post_data->ID; ?>').hide();jQuery('.rc<?php echo $post_data->ID; ?>ty').show();"><?php echo $CORE->_e(array('coupons','46')); ?> </a>
	 
    </div> 
	 
      
      </div>
      </section>   
      
      <div class="clearfix"></div>
      
      <hr />
          
      <div class="clearfix"></div>
      
      

<div class="thumbnail">
<div class="media" style="padding:20px; background:#efefee">
  <div class="media-left">
    <i class="fa fa-envelope-o"></i>
  </div>
  <div class="media-body">
    
<h4 class="media-heading text-left"><?php echo $CORE->_e(array('coupons','21')); ?></h4>
 
<form class="clearfix row" id="mailinglist-form1" name="mailinglist-form1" method="post" onSubmit="IsEmailMailinglist();return false;" style="margin-top:10px;">
             
<div class="col-md-8">
  
<input type="text" class="form-control" name="wlt_mailme1" id="wlt_mailme1" placeholder="example@hotmail.com">

</div>

<div class="col-md-4">
 <button type="submit" class="btn"><?php echo $CORE->_e(array('coupons','22')); ?></button>
</div>

</form>

    
  </div>
</div>

 
    

</div>
      
     <script>
	jQuery(document).ready(function(){
    	jQuery('#wlt_popmodal').modal('show');
		
		jQuery('#<?php echo $_GET['showid']; ?>_clicktoreveal .over').hide();
		jQuery('#<?php echo $_GET['showid']; ?>_clicktoreveal .code').css('text-align','center');
		
	});	
	
	function IsEmailMailinglist(){
		var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
			var de4 	= document.getElementById("wlt_mailme1");
			if(de4.value == ''){
			alert('<?php echo $CORE->_e(array('coupons','23')); ?>');
			de4.style.border = 'thin solid red';
			de4.focus();
			return false;
			}
			if( !pattern.test( de4.value ) ) {	
			alert('<?php echo $CORE->_e(array('coupons','23')); ?>');
			de4.style.border = 'thin solid blue';
			de4.focus();
			return false;
			}
			WLTMailingList('<?php echo str_replace("http://","",get_home_url()); ?>', this.wlt_mailme1.value, 'mailinglist-form1');
		}	
	</script>
        
      </div>
 
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
    
    
    
<?php } ?>
    
    
    
    
    
    
    

	<?php }

	
	function wlt_shortcode_coupon_button( $atts, $content = null  ){
	
		global $userdata, $CORE, $post, $shortcode_tags; $STRING = "";  $default_options = 'text';
		
		if(!isset($GLOBALS['cblock'])){ $cbc = ""; }else{ $cbc = $GLOBALS['cblock']; }
		
		extract( shortcode_atts( array('class' => '' ), $atts ) );
		 
		
		// GET VALUE
		$code = get_post_meta($post->ID,$GLOBALS['CORE_THEME']['coupon']['code_key'],true);		 
		if(is_array($code) && isset($code['code'][0])){ $code = $code['code'][0]; }
		$link = get_post_meta($post->ID,$GLOBALS['CORE_THEME']['coupon']['code_link'],true);
		
		// COUPON TYPE
		$coupon_type = get_post_meta($post->ID,"coupon_type",true);		
		
		// PRINTABLE
		//$can_print = get_post_meta($post->ID,"printable",true);	
		
		// SWITCH COUPON TYPE IF NO COUPON FOUND AND IS SET TO COUPON
		if($code == "" && $coupon_type == 1){			
			$coupon_type = 3;
			update_post_meta($post->ID,"coupon_type",3);
		}
		
		 
		
		// SWITCH THE TYPE OF COUPON
		switch($coupon_type){
		
		case "3": {  // OFFER		
		
			return "<div class='clicktoreveal offer'>
			<a href='".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/' target='_blank' rel='nofollow'>
			<div class='code' style='font-size:16px;'>".$CORE->_e(array('button','12'))." <span class='fa fa-chevron-circle-right' style='width:20px;margin-right: 8px;'></span></div>
			</a>
			</div>";
		
		} break;
		case "2": {  // PRINTABLE CODE
		
			$pl = get_permalink($post->ID);		 
			if(substr($pl,-1) != "/"){ $print_link = $pl."&print=true&amp;pid=".$post->ID; }else{ $print_link = $pl."/?print=true&amp;pid=".$post->ID; }
		
			return "<a href='".$print_link."&amp;iframe=true&amp;width=450&amp;height=500' title='".$post->ID."' data-gal='prettyPhoto' target='_blank' rel='nofollow' class='clicktoreveal printbtn'><div class='over'><span>".$CORE->_e(array('button','23'))."</span></div></a>";
	
		
		} break;		
		default: { // COUPON CODE
		
			// COUPON DISPLAY STYLE
			$coupon_style 	= $GLOBALS['CORE_THEME']['coupon_style'];
			
			// WHICH DISPLAY STYLE
			switch($coupon_style){
					
						case "1": { // CLICK TO REVEAL
						
						
						if($code == ""){
						
							return "<div class='clicktoreveal offer' id='".$post->ID."__".$cbc."clicktoreveal'>
							<div class='code'><span>".$CORE->_e(array('coupons','34'))."</span> <span class='fa fa-chevron-circle-right' style='width:20px;margin-right: 8px;'></span></div>
							 
							</div>
							
							<script>
							jQuery('#".$post->ID."__".$cbc."clicktoreveal').on( \"click\", function() {					 
							window.open(  '".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/',  '_blank' );					});
							
							</script>
							";
							}else{
							
								return "<div class='clicktoreveal green' id='".$post->ID."_".$cbc."_clicktoreveal'>
								<div class='over'><span>".$CORE->_e(array('coupons','35'))."</span></div>
								<div class='code'>".$code."</div>
								</div>
								
								<script>
								jQuery('#".$post->ID."_".$cbc."_clicktoreveal').on( \"click\", function() {						
								jQuery('#".$post->ID."_".$cbc."_clicktoreveal .over').hide();
								jQuery('#".$post->ID."_".$cbc."_clicktoreveal .code').css('text-align','center');						
								window.open(  '".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/',  '_blank' );
								});						
								</script>
								";
							
							}
						
						
						
						} break;
						
						case "3": { // CLICK TO COPY 
						
						return "<div class='clicktoreveal green' id='".$post->ID."_".$cbc."_clicktoreveal'>
								 
								<div class='code' style='text-align: center;' id='coupon_code_feat_".$post->ID."'>".$code."</div>
								
								</div>
								
								
								<script language='javascript' type='text/javascript'>
								
								 jQuery(document).ready(function(){
								 
								 jQuery('#coupon_code_feat_".$post->ID."').zclip({				
										path:'".get_template_directory_uri().'/templates/'.get_option('wlt_base_theme')."/js/ZeroClipboard.swf',
										copy:jQuery('#coupon_code_feat_".$post->ID."').text(),
										afterCopy:function(){
											window.open(  '".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/',  '_blank' );
										}	
									}); 
									 
								});
								
								jQuery('#wlt_search_tab2').on( 'click', function() {
								
									jQuery('#coupon_code_feat_".$post->ID."').zclip('remove');  
									setTimeout(function(){ 				
										jQuery('#coupon_code_feat_".$post->ID."').zclip({				
											path:'".get_template_directory_uri().'/templates/'.get_option('wlt_base_theme')."/js/ZeroClipboard.swf',
											copy:jQuery('#coupon_code_feat_".$post->ID."').text(),
											afterCopy:function(){
												window.open(  '".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/',  '_blank' );
											}	
										}); 				
									
									}, 1000);
									
								});
								 
								
								</script>";
					 
					 
						
						} break;
						
						default: {
						
							if(trim($code) == ""){ $code = $CORE->_e(array('coupons','40')); } 
					
							// GET CURRENT PAGE LINK
							$currentlink = $CORE->format_webpath('');
							 
							return "<div class='clicktoreveal green' id='".$post->ID."_".$cbc."_clicktoreveal'>
										<div class='over'><span>".$CORE->_e(array('coupons','35'))."</span></div>
										<div class='code'>".$code."</div>
										</div>
										
										<script>
										jQuery('#".$post->ID."_".$cbc."_clicktoreveal').on( \"click\", function() {						
										window.location.href='".get_home_url()."/out/".$post->ID."/".$GLOBALS['CORE_THEME']['coupon']['code_link']."/';	
										var win = window.open(  '". $currentlink ."couponid=".$post->ID."&showid=".$post->ID."_".$cbc."#itemid".$post->ID."',  '_blank' );						
										this.window.focus(); 
										}); 
										</script>
										"; 
						
						
						} break;
					
					}
		
		
		}
		
		}	
		
	 
	}
	function wlt_shortcode_stores( $atts, $content = null ) {
	
			global $userdata, $CORE, $post, $shortcode_tags; 
		
			extract( shortcode_atts( array('icon' => "yes", 'limit' => 100, 'perrow' => 4, 'screenshot' => "no"  ), $atts ) );
			 
			return do_shortcode('[TAXONOMY name=store icon='.$icon.' limit='.$limit.' perrow='.$perrow.']');
	}	
	function wlt_shortcode_store( $atts, $content = null ) {
	
			global $userdata, $CORE, $post, $shortcode_tags; $STRING = "";  $default_options = 'text';
		
			extract( shortcode_atts( array('text' => $default_options  ), $atts ) );
			 
			$store = "";
			$store_list = get_the_terms($post->ID, "store" );
			if(is_array($store_list)){
				foreach($store_list as $st){
					$store .= "<span class='wlt_shortcode_store'><a href='".get_term_link($st->slug, "store")."'>".esc_attr($text)."".$st->name."</a></span>";
				}	
			return $store;
			}
	}
	 
	function wlt_shortcode_coupon_starts( $atts, $content = null ) {
	
			global $userdata, $CORE, $post, $shortcode_tags; $STRING = "";  $default_options = 'text';
		
			extract( shortcode_atts( array('text' => $default_options  ), $atts ) );
			$options = explode("|",esc_attr($type));
			// GET VALUE
			$date = get_post_meta($post->ID,'start_date',true);
			// ADD IN END DTATE IF NONE IS SET
			if($date == ""){ $STRING = "recently"; }else{  $STRING = esc_attr($text)."".hook_date($date); }
			// RETURN VALUE
			return "<span class='wlt_shortcodes_start_date'>".$STRING."</span>"; 
	}
	
	function wlt_shortcode_coupon_ends( $atts, $content = null ) {
	
			global $userdata, $wpdb, $CORE, $post, $shortcode_tags; $STRING = ""; 
		
			extract( shortcode_atts( array('text' => "", 'id' => '', 'small' => false  ), $atts ) );
			 
			$id = esc_attr($id);
			// WHICH ID TO USE
			if($id != "" && is_numeric($id)){ $ThisId = $id; }else{ $ThisId = $post->ID; }
			
			// GET VALUE
			$date = get_post_meta($ThisId,'expiry_date',true);
			if($date == ""){
			$date = $wpdb->get_var( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id =('".$ThisId."') AND meta_key=('expiry_date') LIMIT 1" );
			}
			
			// GET DATE PARTS
			$vv = $CORE->TimeDiff($date);	
			
			if($vv['date'] == ""){
				 	$STRING = $CORE->_e(array('coupons','39'));
			}elseif($vv['expired']){					
				$STRING = $CORE->_e(array('coupons','18')); 
			}else{
				$STRING =  $CORE->_e(array('coupons','37'))."".$vv['date']; 
			}
			 
			// RETURN VALUE
			return "<span class='wlt_shortcodes_expiry_date'>".$STRING."</span>";  
	} 
	 
	// ADD A NEW coupon SHROTCODE
	function wlt_coupon_new_tags(){
		echo "<br />[CBUTTON] - Displays The Get Coupon Button";
	echo "<br />[COUPON] - Displays The Coupon";
	echo "<br/>[COUPON_START] - Shows the start date of the coupon";
	echo "<br/>[COUPON_END] - Shows the expiry of the coupon";
	echo "<br/>[STORE] - Shows the coupon store";
	}
	
	 
	//1. HOOK INTO THE ADMIN MENU TO CREATE A NEW TAB
	function _hook_admin_1_pagesetup(){  global $wpdb, $CORE; $core_admin_values = get_option("core_admin_values");  ?>
	
    <div class="accordion-group">
    <div class="accordion-heading" style="background:#fff;">
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#pagesetup_according" href="#extra1">
         <h4 style="margin:0xp;font-weight:bold;">
         <img src="<?php echo get_template_directory_uri(); ?>/framework/admin/img/icons/set.png">
        Coupon Settings <span style="font-size:12px;">(view/hide)</span></h4> 
        </a>
    </div>
    
    <div id="extra1" class="accordion-body collapse">
    <div class="accordion-inner">
    <div class="innerwrap content">
    
    
     <div class="heading2">Coupon Display Type</div>   
     
     
     <div class="form-row control-group row-fluid ">
	
		<label class="control-label span6"><b>Coupon Button Type</b></label>
	
		 <div class="span6">	
		<select data-placeholder="Choose a value..." class="chzn-select" name="admin_values[coupon_style]">
		<option value="1" <?php if($core_admin_values['coupon_style'] == '1'){ echo "selected=selected"; } ?>>Click to reveal</option>
		<option value="2" <?php if($core_admin_values['coupon_style'] == '2'){ echo "selected=selected"; } ?>>Click to open</option>
		 <option value="3" <?php if($core_admin_values['coupon_style'] == '3'){ echo "selected=selected"; } ?>>Click to copy</option>
		</select>
        </div>
				   
	 </div>  
    
    
    
    
    
    
    
    
    
    
    
    <div class="heading2">Coupon Field Mapping</div>
    
    <div class="row-fluid">
    <div class="span6"> 
	
	<div class="form-row control-group row-fluid ">
	
		<label class="control-label"><b>Coupon Field Mapping</b></label>
	
		<small>Select the custom field which will be used to store coupon codes.</small>
					
		<select data-placeholder="Choose a value..." class="chzn-select" name="admin_values[coupon][code_key]">
		<option value=""></option>
		<?php
			echo $CORE->CUSTOMFIELDLIST(esc_attr( $core_admin_values['coupon']['code_key'] ) );
		?> 
		</select>
				   
	 </div> 
	
    </div><div class="span6"> 
	
	<div class="form-row control-group row-fluid ">
	
		<label class="control-label"><b>Coupon Link Field Mapping</b></label>
	
		<small>Select the custom field which will be used to store coupon button links.</small>
					
		<select data-placeholder="Choose a value..." class="chzn-select" name="admin_values[coupon][code_link]">
		<option value=""></option>
		<?php
			echo $CORE->CUSTOMFIELDLIST(esc_attr( $core_admin_values['coupon']['code_link'] ) );
		?> 
		</select>
				   
	 </div> 
     </div></div>
     
     

     
     
     
     
     
     
     
     <div class="heading2">Coupon Pop-up Window</div>
     
     
      <div class="form-row control-group row-fluid ">
                            <label class="control-label span6" rel="tooltip" data-original-title="Turn on if you want the newsletter form to be displayed at the bottom of your coupon pop-up window." data-placement="top">Display Newsletter Form</label>
                            <div class="controls span5">
                              <div class="row-fluid">
                                <div class="pull-left">
                                  <label class="radio off">
                                  <input type="radio" name="toggle" 
                                  value="0" onChange="document.getElementById('coupon_popup_newsletter').value='0'">
                                  </label>
                                  <label class="radio on">
                                  <input type="radio" name="toggle"
                                  value="1" onChange="document.getElementById('coupon_popup_newsletter').value='1'">
                                  </label>
                                  <div class="toggle <?php if($core_admin_values['coupon_popup_newsletter'] == '1'){  ?>on<?php } ?>">
                                    <div class="yes">ON</div>
                                    <div class="switch"></div>
                                    <div class="no">OFF</div>
                                  </div>
                                </div> 
                               </div>
                             </div>
                             
                             <input type="hidden" class="row-fluid" id="coupon_popup_newsletter" name="admin_values[coupon_popup_newsletter]" 
                             value="<?php echo $core_admin_values['coupon_popup_newsletter']; ?>">
            </div>       
            
            <div class="form-row control-group row-fluid">
            
                <label class="control-label">Custom HTML/Shortcodes</label>   
                <div class="controls">    
                <textarea class="row-fluid" style="height:100px; font-size:11px;" name="adminArray[coupon_popup_custom]"><?php echo stripslashes(get_option('coupon_popup_custom')); ?></textarea>    	 
                </div>
            </div> 
            
            
            <div class="heading2">Coupon Settings</div>
     
            
                  <div class="form-row control-group row-fluid ">
                            <label class="control-label span6" rel="tooltip" data-original-title="Turn on if you want to remove the hardcoded coupon fields." data-placement="top">Disable Default Fields</label>
                            <div class="controls span5">
                              <div class="row-fluid">
                                <div class="pull-left">
                                  <label class="radio off">
                                  <input type="radio" name="toggle" 
                                  value="0" onChange="document.getElementById('coupon_defaults').value='0'">
                                  </label>
                                  <label class="radio on">
                                  <input type="radio" name="toggle"
                                  value="1" onChange="document.getElementById('coupon_defaults').value='1'">
                                  </label>
                                  <div class="toggle <?php if(get_option('coupon_defaults') == '1'){  ?>on<?php } ?>">
                                    <div class="yes">ON</div>
                                    <div class="switch"></div>
                                    <div class="no">OFF</div>
                                  </div>
                                </div> 
                               </div>
                             </div>
                             
                             <input type="hidden" class="row-fluid" id="coupon_defaults" name="adminArray[coupon_defaults]" 
                             value="<?php echo get_option('coupon_defaults'); ?>">
            </div>  
            
            
            
            
            
                  <div class="form-row control-group row-fluid ">
                            <label class="control-label span6" rel="tooltip" data-original-title="Turn on if you want to show the image instead of the discount box" data-placement="top">Show image instead of discount</label>
                            <div class="controls span5">
                              <div class="row-fluid">
                                <div class="pull-left">
                                  <label class="radio off">
                                  <input type="radio" name="toggle" 
                                  value="0" onChange="document.getElementById('coupon_showimage').value='0'">
                                  </label>
                                  <label class="radio on">
                                  <input type="radio" name="toggle"
                                  value="1" onChange="document.getElementById('coupon_showimage').value='1'">
                                  </label>
                                  <div class="toggle <?php if(get_option('coupon_showimage') == '1'){  ?>on<?php } ?>">
                                    <div class="yes">ON</div>
                                    <div class="switch"></div>
                                    <div class="no">OFF</div>
                                  </div>
                                </div> 
                               </div>
                             </div>
                             
                             <input type="hidden" class="row-fluid" id="coupon_showimage" name="adminArray[coupon_showimage]" 
                             value="<?php echo get_option('coupon_showimage'); ?>">
            </div> 
            
            
            
            
            
            
            
            
    </div> </div> </div> </div>
    
    
    
    
    
    
	<?php	
	}
	
	
	// ADD IN HOOK FOR FALLBACK IMAGE
	function wlt_coupon_fallback_image_tostore($c){ global $post;	
	// GET ID FROM NO-IMAGE STRING
	$b = explode('no-image-',$c);
	$b1 = explode('"',$b[1]);
 
	if(!is_numeric($b1[0])){ return $c; } 
	$terms = wp_get_post_terms( $b1[0], 'store', array("fields" => "all") ); 
	// CHECK IF THE STORE ASSIGNED HAS AN ICON
	 
	if(isset($terms[0]->term_id) && isset($GLOBALS['CORE_THEME']['category_icon_'.$terms[0]->term_id]) ){
	$merchant_logo = $GLOBALS['CORE_THEME']['category_icon_'.$terms[0]->term_id];
	return "<img src='".str_replace("&","&amp;",$merchant_logo)."' alt='merchant' class='wlt_thumbnail img-responsive storelogo' />";
	}
	 
	return $c;
	}
	
	
	
	
	
	
	
	function _hook_content_listing_class($c){ global $post; 
		
		// CHECK IF ITS EXPIRED
		$date = get_post_meta($post->ID,'expiry_date',true);
		if($date != "" && strtotime($date) < strtotime(current_time( 'mysql' )) ) {
		$c .= " expired";
		}		
		return $c;	
	}
	function _customsearch(){	
  
		if(isset($_GET['storeid']) && is_numeric($_GET['storeid']) ){
			// ADD ON TAXONOMY QUERY FOR STORE
			$GLOBALS['taxonomies'][] = array(
					'taxonomy' => 'store',
					'field' => 'term_id',
					'terms' => array( $_GET['storeid'] ),
					'operator'=> 'IN'						
			);
		}	
	}
	function _hook_custom_query($c){
 
	
	if(isset($GLOBALS['CORE_THEME']['hide_expired']) && $GLOBALS['CORE_THEME']['hide_expired'] == '1' && $GLOBALS['CORE_THEME']['coupon_defaults'] != 1){	
		
		$args = array( 
			'post_type' => THEME_TAXONOMY."_type",			
			'meta_query' => array(
			array(
					'key' => 'expiry_date',
					'orderby' => 'meta_value',						 
					'compare' => '>=',
					'value' => date('Y-m-d H:i:s'),
					'type' => 'DATETIME'
					),
			),		 
		); 
		
	
		// MERGE VALUES
		if(is_array($c)){
			$c = array_merge($c,$args);
		}
	
	}
	
	
	return $c;
	}
	
	
	
	
	
	
	
 	
	
} // END CLASS FILE

















/* =============================================================================
	  STORE WIDGET CLASS
	========================================================================== */
 
class core_widgets_stores extends WP_Widget {

    function core_widgets_stores() {
        // widget actual processes		
		$opts = array(
			'classname' => 'core_widgets_stores',
			'description' => 'Display Stores.' 
		);
		parent::__construct( 'core_widgets_stores', '[WLT-COUPON] Store List' , $opts );
		
    }

    function form($instance) {
	
	global $wpdb, $CORE;
	
 		$defaults = array(
			'title'		=> 'Website Stores',		
		);		
		$instance = wp_parse_args( $instance, $defaults );  
	
	 ?>
     
 	<p><b>Title</b></p>
	<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $instance['title'] ); ?>" />
  
   <p><br /><b>Select Stores to Display</b> (Hold Shift+Ctrl to select multiple)</p>  
      <select id="<?php echo $this->get_field_id( 'storeID' ); ?>" name="<?php echo $this->get_field_name( 'storeID' ); ?>[]" multiple="multiple" style="width:100%; height:150px;">
      <?php echo $CORE->categorylist(array($instance['storeID'],false,0,"store")); ?>
    </select> 
  
     <?php
	 
    $out = '<br /><br /><p class="inline"> <input id="' . $this->get_field_id('parentonly') . '" name="' . $this->get_field_name('parentonly') . '" type="checkbox" ' . checked(isset($instance['parentonly'])? $instance['parentonly']: 0, true, false) . ' />';
	$out .= ' &nbsp;&nbsp; <label for="' . $this->get_field_id('parentonly') . '">Show Store Image </label></p>';
	echo $out;
 
    }

	function update( $new, $old ){	
	
		$clean = $old;		
		$clean['title'] = isset( $new['title'] ) ? strip_tags( esc_html( $new['title'] ) ) : '';	
		$clean['parentonly'] = isset( $new['parentonly'] ) ? '1' : '0';	
		$clean['storeID'] = $new['storeID'];
		return $clean;
	}

    function widget($args, $instance) {

		global $CORE; $STRING = ""; $COUNTER = 2; @extract($args); $core_admin_values = get_option("core_admin_values"); if(!is_array($instance['storeID'])){ $instance['storeID'] = array(); } 
		
  
 			echo "<div class='core_widgets_stores_list'>".$before_widget.$before_title.$instance['title']."</div>"; 
	
			$categories = get_categories(array('taxonomy' => "store",'hide_empty'=> 0,'hierarchical'=> 0,'use_desc_for_title'=> 1,'pad_counts'=> 1, "orderby" => "count", "order"=>"desc")); 
  			foreach ($categories as $category) {
			
			if(!in_array($category->term_id, $instance['storeID'])){ continue; }
			
				// DISPLAY ICONS
				if($instance['parentonly']){
					
						if(isset($core_admin_values['category_icon_'.$category->term_id]) && strlen($core_admin_values['category_icon_'.$category->term_id]) > 5){
						$image = $core_admin_values['category_icon_'.$category->term_id];			
						}else{
						$image = FRAMREWORK_URI.'img/img_fallback.jpg';
						}
						$image = str_replace("&","&amp;",$image);
						
						$link = get_term_link($category->slug, 'store');
						echo "
						<div class='storediv col-md-6 text-center'>
						<div class='cwrap'>
						<a href='".$link."'><img src='".$image."' alt='".$category->name."' class='wlt_thumbnail' /></a>
						<div class='clearfix'></div>
					 
						<div class='stitle'><a href='".$link."'>".$category->name."</a></div>
						<p>".$category->count." ".$CORE->_e(array('coupons','31'))."</p>
						</div> 
						</div>	
						";				 
						
				}else{
					echo '<a class="list" href="'.get_term_link($category->slug, 'store').'"><span>'.$category->name.'</span></a>'; 
				}
		 
			
			}
			
			echo $after_widget;  
 
    }

}

?>