<?php 


function dapcondcontdrip_register_settings() {
	add_option( 'dapcondcontdrip_hasaccessto', '1');
	add_option( 'dapcondcontdrip_confirmmsg', 'Are you sure you want to proceed?');
	add_option( 'dapcondcontdrip_completedmsg', 'Congrats! You have Completed this Course!');
	register_setting( 'default', 'dapcondcontdrip_hasaccessto' ); 
	register_setting( 'default', 'dapcondcontdrip_confirmmsg' ); 
	register_setting( 'default', 'dapcondcontdrip_completedmsg' ); 
} 
add_action( 'admin_init', 'dapcondcontdrip_register_settings' );
 
function dapcondcontdrip_register_options_page() {
	add_options_page('DAP Conditional Drip Setting', 'DAP Conditional Drip Setting', 'manage_options', 'dapcondcontdrip-options', 'dapcondcontdrip_options_page');
}
add_action('admin_menu', 'dapcondcontdrip_register_options_page');
 
function dapcondcontdrip_options_page() {
	?>
<div class="wrap">
	<?php screen_icon(); ?>
	<h2>DAP Conditional Content Drip Setting</h2>
	<form method="post" action="options.php"> 
		<?php settings_fields( 'default' ); ?>
			<p>Set default values for the conditional drip fields</p>
			<table class="form-table">
				<tr valign="top">
					<th style='width:250px' scope="row"><label style='width:100px' for="dapcondcontdrip_hasaccessto">Has Access To (DAP Product ID)</label></th>
					<td><input type="text" size=5 id="dapcondcontdrip_hasaccessto" name="dapcondcontdrip_hasaccessto" value="<?php echo get_option('dapcondcontdrip_hasaccessto'); ?>" /></td>
				</tr>
				<tr valign="top">
					<th style='width:250px' scope="row"><label style='width:100px' for="dapcondcontdrip_confirmmsg">Course Proceed Confirmation Message</label></th>
					<td><input type="text" size="52" id="dapcondcontdrip_confirmmsg" name="dapcondcontdrip_confirmmsg" value="<?php echo get_option('dapcondcontdrip_confirmmsg'); ?>" /></td>
				</tr>
                
                <tr valign="top">
					<th style='width:250px' scope="row"><label style='width:100px' for="dapcondcontdrip_completedmsg">Course Completed Message</label></th>
					<td><textarea id="dapcondcontdrip_completedmsg" name="dapcondcontdrip_completedmsg" rows="5" cols="50"><?php  echo get_option('dapcondcontdrip_completedmsg');?></textarea></td>
				</tr>
                
			</table>
		<?php submit_button(); ?>
	</form>
</div>
<?php
}


/*Add this code to your functions.php file of current theme OR plugin file if you're making a plugin*/
//add the button to the tinymce editor
add_action('media_buttons_context','add_conddrip_tinymce_media_button');
function add_conddrip_tinymce_media_button($context){

return $context.=__("
<a href=\"#TB_inline?width=480&inlineId=conddrip_shortcode_popup&width=640&height=513\" class=\"button thickbox\" id=\"conddrip_shortcode_popup_button\" title=\"Add Conditional Drip Short Code\">Add Conditional Drip Code</a>");
}

add_action('admin_footer','conddrip_shortcode_media_button_popup');
//Generate inline content for the popup window when the "my shortcode" button is clicked
function conddrip_shortcode_media_button_popup(){?>
  <div id="conddrip_shortcode_popup" style="display:none;">
    <--".wrap" class div is needed to make thickbox content look good-->
    <div class="wrap">
      <div>
        <h2>Insert My Shortcode</h2>
        <div class="conddrip_shortcode_add"><br />
		<div> Product ID: <input type="text" id="hasAccessTo" value="<?php echo get_option('dapcondcontdrip_hasaccessto'); ?>"> </div><br />
		<div> Confirm Message: <input type="text"  size="52" id="confirmMsg" value="<?php echo get_option('dapcondcontdrip_confirmmsg'); ?>"></div><br />
		<div> Completed Message:<br /><br /><textarea id="completedMsg" name="completedMsg" rows="5" cols="50"><?php  echo get_option('dapcondcontdrip_completedmsg');?></textarea>  </div><br />
		  
		  <button class="button-primary" id="conddripgenscbtn">Generate Shortcode</button>
        </div>
      </div>
    </div>
  </div>
<?php
}

//javascript code needed to make shortcode appear in TinyMCE edtor
add_action('admin_footer','my_shortcode_add_shortcode_to_editor');
function my_shortcode_add_shortcode_to_editor(){?>
<script>
jQuery('#conddripgenscbtn').on('click',function(){
  var hasAccessTo = jQuery('#hasAccessTo').val();
  var confirmMsg = escape(jQuery('#confirmMsg').val());
  var completedMsg = escape(jQuery('#completedMsg').val());

  
  var shortcode = '[DAP-CondDrip hasAccessTo="'+hasAccessTo+'" confirmMsg="'+confirmMsg+'" completedMsg="'+completedMsg+'" /]<br>';
 
 
//  tinyMCE.activeEditor.execCommand( 'mceInsertContent', false, shortcode );
 if( !tinyMCE.activeEditor || tinyMCE.activeEditor.isHidden()) {
//    jQuery('textarea#content').val(shortcode);
	  // var original_text = jQuery('textarea.wp-editor-area').val(); 
	   //jQuery('textarea.wp-editor-area').val(original_text + '\r\n' + shortcode); 
	   //jQuery( '#wp-content-editor-container' ).find( 'textarea' ).val( shortcode );
		send_to_editor(shortcode);
  } else {
    tinyMCE.execCommand('mceInsertContent', false, shortcode);
  }
  
  //close the thickbox after adding shortcode to editor
  self.parent.tb_remove();
});
</script>
<?php
}



add_filter('widget_text', 'do_shortcode');
add_shortcode('DAP-CondDrip', 'dap_conddrip');


function dap_conddrip($atts, $content=null){ 
	extract(shortcode_atts(array(
		'hasaccessto' => '',
		'confirmmsg'=>'Are you ready to move on to the next Module ?',
		'completedmsg'=>''
		
	), $atts));
		
	//$markascompleteimageurl=urldecode($markascompleteimageurl);
	$confirmmsg=urldecode($confirmmsg);
	if($certimageurl=="")
		$certimageurl=urldecode($certimageurl);
	$completedmsg=urldecode($completedmsg);
	
	logToFile("DAP-CondDrip: ENTER: completedmsg=".$completedmsg);
	
	$content = do_shortcode($content);
	$content = dap_clean_shortcode_content($content);	
	
	$content='<link rel="stylesheet" href="http://bookdrip.com/wp-content/plugins/DAP-WP-LiveLinks/includes/condcontdrip/template1/css/condcontentdrip.css?ver=1"/>'.$content;
	
	$session = Dap_Session::getSession();
	$user = $session->getUser();

	if( (!Dap_Session::isLoggedIn()) && (!isset($user)) ) {
		logToFile("DAP-CondDrip: Shortcode says this is be shown only to those NOT logged in - and this person is NOT logged in, so return content and stop");
		return $content;
	}
	
	if($hasaccessto=="") {
		logToFile("DAP-CondDrip: Mising hasaccessto in the conddrip shortcode");
		return $content;	
	}
	
	$userId = $user->getId();
	//Arriving here means user is logged in
	logToFile("DAP-CondDrip::User is valid and logged in. Userid: " . $user->getId());	

	$productIds=explode(",",$hasaccessto);
	$found=false;
	foreach($productIds as $productId) {
		$product = Dap_Product::loadProduct($productId);
		if (isset($product)) {
			$condDripProduct=$product->getDrip_type();
			logToFile("DAP-CondDrip: check if cond drip product: " . $condDripProduct);
			if($condDripProduct==2) {
				if(!$user->hasAccessTo($productId)) {
					logToFile("DAP-CondDrip: yes $productId is a cond drip product but user does not have access to it. Return.");
					continue;
				}
				logToFile("DAP-CondDrip: yes $productId is a cond drip product AND the user has access to it. Show the button to proceed to next course.");
				$found=true;
				break;
			}
		}
		else continue;
	}
	
	if($found==false) {
		logToFile("DAP-CondDrip: did not find any eligible products for cond drip. Return.");
		return $content;	
	}
	
	global $wpdb, $post, $table_prefix;
	if ($post->ID) {
		$current_postid=$post->ID;
		$post_id = get_post($current_postid); 
		$permalink =  get_permalink( $post_id ); 	
		logToFile("DAP-CondDrip: post permalink is : " . $permalink);
		$permalink = $_SERVER['REQUEST_URI'];
		logToFile("DAP-CondDrip: request uri, before remove query string permalink is : " . $permalink);
		$permalink=removeQueryStringDSH($permalink);
		logToFile("DAP-CondDrip: request uri, remove query string permalink is : " . $permalink);
	} 
	else {
		logToFile("DAP-CondDrip: can't proceed without the permalink. Return.");
		return $content;
	}
	
	//check if user has access to this content
	
	$resourceId=Dap_UserCondDrip::checkUserAccessToResourceTitle($userId, $productId, $permalink);
	logToFile("DAP-CondDrip: resourceId=".$resourceId);

	if($resourceId==-2) {
		logToFile("DAP-CondDrip: user already has access and has moved to next course (passed status): $userId, $productId, $resurl, $resourceId. Return.");
		
		if($completedmsg != "") 
			$content .= urldecode($completedmsg);	
		
		if(	$certimageurl!="") {
			$completedcert = '<img src="'.$certimageurl.'" border="0" \>';
			$content .= $completedcert;
		}
		
		return $content;
	}
	else if($resourceId>0) {
	  // user-prod-resource already exist in usercond table but result is still null or empty, its not set to P
	  $qstr="productid=".$productId."&resid=".$resourceId."&redirect=".$_SERVER["REQUEST_URI"];
	  
	  $linkstr='<a class="condButton" href=\'' . "/dap/dapconddrip.php?" . $qstr.'\' onclick="return confirm(\''.$confirmmsg.'\');">Mark As Complete</a>';	
	  
	  logToFile("DAP-CondDrip: show the IAMDONE button, linkstr: ".$linkstr);  
	  $content .=  $linkstr;  
	}
	else 
	  logToFile("DAP-CondDrip: no row in the table.. user should not see this button");
	 
	$cssurl=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/condcontdrip/template1/css/condcontentdrip.css?ver=1";
	return  $content;
}


?>