<?php
 
class core_microjobs extends white_label_themes {
 
	function core_microjobs(){	
	
		// hide myaccount orders
		define('HIDE_MYACCOUNT_ORDERS',true);
 
 		
		register_post_type( 'ppt_workflow', 
					array(
					'hierarchical' => true,	
					  'labels' => array('name' => 'Workflows'),
					  'public' => true,
					  'query_var' => true,
					  'show_ui' => true, // dont show UI
					  'rewrite' => array('slug' => 'workflow')	,
					   'supports' => array ( 'title',  'custom-fields'  ),    
			 
		) );
				
				
		
		if(is_admin()){	
		
			add_action('hook_fieldlist_0', array($this, '_extra_fields' ) );
		 
			add_action('hook_admin_1_pagesetup', array($this, '_hook_admin_1_pagesetup'  ) ); 
		}
		
		// ADD LISTING EXTRAS
		add_action('hook_add_listdata',  array($this, '_hook_add_listdata' ) );
		add_action('hook_add_listtitles',  array($this, '_hook_add_listtitles' ) );
		add_action('hook_add_form_post_save', array($this, '_hook_add_form_post_save' ) );		
		
		// SAVE WORKFLOW FUNCTIONS
		add_action('init', array($this, 'jobs_savefunctions' ) );	
  		
		// HOOK ORDERS
		add_action('hook_account_orders_table',	 array($this, 'MYORDERS' ) );	
 
 		// MY ACCOUNT HOOKS
		add_action('hook_account_after', array($this, 'jb_usermenu_after' ) );
		add_action('hook_account_pagelist', array($this, '_hook_account_pagelist' ) );
		
 		// HOOK CUSTOM FIELDS
		add_action('hook_add_fieldlist',  array($this, '_hook_customfields' ) );
		
		// HOOK EMAILS
		add_action('hook_email_list', array($this, 'add_new_emails' ) ); 
		
		// HOOK CALLBACK TYPE
		add_action('hook_callback_process_orderid_after', array($this, 'hook_callback_process_orderid_after' ) );
	  	
		// HOK ADD LISTING POST TITLE TEXT
		add_action('hook_add_post_title_text', array($this, 'hook_add_post_title_text'));		
		
		// COUPON ACTIVATED SHORTCODES	
		add_shortcode( 'BUYBAR', array($this,'shortcode_buybar') );
 		add_shortcode( 'INFOBAR', array($this,'shortcode_infobar') );
 		add_shortcode( 'SALES', array($this,'shortcode_sales') );		
 		add_shortcode( 'WORKFLOW', array($this,'shortcode_workflow') );
		
}

function _hook_account_pagelist($c){

global $CORE;

$old = $c[1];

$c[1] = array(
	"l" => "#top",	
	"oc" => "jQuery('#MyAccountBlock').hide();jQuery('#MyMJobs').show();",
	"i" => "glyphicon glyphicon-thumbs-up",
	"t" => $CORE->_e(array('mjob','40')),
	"d" => $CORE->_e(array('mjob','41')),
	"e" => "",
);
$c[] = $old;


return $c;

}
	
function _hook_add_form_post_save(){

	///////////////
	update_post_meta($GLOBALS['POSTID'], 'customextras', $_POST['customextras']);
}



 
 
 
	
function shortcode_buybar(){ global $userdata, $post, $CORE; $STRING = '';

	// GET PRICE
	$price = get_post_meta($post->ID, 'price', true);
	
	// GET THE CURRENT SALES AMOUNT
	$sales_count = get_post_meta($post->ID, 'sales_count', true);
	$purchase_type = get_post_meta($post->ID, 'purchase_type', true);
?>

<script>
function AdjustPrice(price, g){

	jQuery('#customextraslist li').removeClass('active');
	jQuery(g).addClass('active');
	
	jQuery('#finalprice1').html('<?php echo $GLOBALS['CORE_THEME']['currency']['symbol']; ?>'+price);
	
	jQuery('#paypalAmount').val(price);
	jQuery('#credit_total').val(price);
	jQuery('#admin_test_total').val(price);
	
	jQuery('#totalpricevalue').html('<?php echo $GLOBALS['CORE_THEME']['currency']['symbol']; ?>'+price);
	
	
}

</script>

<?php

//CHECK FOR CUSTOM ADDONS
$current_data = get_post_meta($post->ID,'customextras', true); 
if(is_array($current_data) && !empty($current_data) && $current_data['name'][0] != "" ){ $i=0; 


$STRING .= '<section id="job_addons">';

$STRING .= '<h4>'.$CORE->_e(array('mjob','43')).'</h4>';

$STRING .= '<ul id="customextraslist" class="list-group">';

$STRING .= '<li class="list-group-item" onclick="AdjustPrice('.$price.')" style="cursor:pointer; text-align:right;"> <i class="fa fa-close"></i> '.$CORE->_e(array('mjob','32')).' </li>';

	foreach($current_data['name'] as $data){ 
	
		if($current_data['name'][$i] !="" && is_numeric($current_data['price'][$i]) ){
	  
			$STRING .= '<li class="list-group-item" onclick="AdjustPrice('.($price + $current_data['price'][$i]).', this)" style="cursor:pointer;"> 
			
			<i class="glyphicon glyphicon-ok-sign"></i>
			  
			<span class="pull-right label label-success">+ '.hook_price($current_data['price'][$i]).'</span>
			  
			<strong>'.$current_data['name'][$i].'</strong>
			 
			<p>'.trim($current_data['value'][$i]).'</p>
			   
			</li>';
	
		} 

	$i++; 
	}

$STRING .= '</ul>';
$STRING .= '</section>';
} 
 
  
  
$STRING .= "<div class='buyjobbox text-center'>";
// CHEECK IF THIS LISTING IS A 1 TIME PURCHASE OR MULTIPLE PURCHASE
if($sales_count > 0 && $purchase_type == 1){

	$STRING .= $CORE->_e(array('mjob','31'));

}else{


	
	if(is_numeric($price)){
		if($userdata){
	 
		if($userdata->ID == $post->post_author){
		
		// NO BIDDING ON OWN ITEMS
		$STRING .= '<button class="btn btn-lg btn-success" href="javascript:void(0);" onclick="alert(\''.$CORE->_e(array('auction','54')).'\');" role="button" type="button">'.$CORE->_e(array('auction','55')).' <span id="finalprice1">('.hook_price($price).')</span></button>';
		
		}else{
		
		$STRING .= '<button class="btn btn-lg btn-success" href="#microjobpayment" role="button" type="button" data-toggle="modal">'.$CORE->_e(array('auction','55')).' <span id="finalprice1">('.hook_price($price).')</span> </button>';
		
		}
		
		
		}else{
		
		$STRING .='<a class="btn btn-lg btn-success" href="'.site_url('wp-login.php?redirect='.get_permalink($post->ID), 'login_post').'">'.$CORE->_e(array('auction','55')).' ('.hook_price($price).')</a>';
		}
		
	}
	
	
	if($userdata && is_numeric($price) && $userdata->ID != $post->post_author  ){
	$STRING .= '<!-- Payment Modal -->
	<div id="microjobpayment" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog"><div class="modal-content">
	  <div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
		<h4 class="modal-title">'.$CORE->_e(array('single','13')).' (<span id="totalpricevalue">'.hook_price($price).'</span>)</h4>
	  </div>
	  <div class="modal-body">'.$this->PAYMENTS(round($price,2), "MJ-".$post->ID."-".$userdata->ID."-".date("YmdHis"), $post->post_title, $post->ID, $subscription = false).'</div>
	  <div class="modal-footer">
	  '.$this->admin_test_checkout().'
	  <button type="button" class="btn btn-default" data-dismiss="modal" aria-hidden="true">'.$CORE->_e(array('single','14')).'</button></div></div>
	  </div></div>
	<!-- End Modal -->';
	}
	
}
$STRING .= '</div>';
return $STRING;


}
	
	

function shortcode_infobar(){ global $post, $userdata, $CORE;	
		
	// GET FEEDBACK RATING	
	$fback = $CORE->FEEDBACKSCORE($post->ID); 
	
	// BUILD OUTPUT
	$STRING = ' 
	<div class="clearfix"></div>
	
	<div id="infobarbox_wrap">
	
		<ul class="list-inline" id="infobarbox">
		
			<li class="col-md-3"> <span>'.get_post_meta($post->ID,'days',true).' '.$CORE->_e(array('date','days')).'</span> '.$CORE->_e(array('mjob','26')).': </li>
			<li class="col-md-3"> <span>'.$fback['score'].'%</span> '.$CORE->_e(array('mjob','27')).' ('.$fback['votes'].' '.$CORE->_e(array('mjob','28')).')</li>
			<li class="col-md-3"> <span>'.do_shortcode('[SALES]').'</span> '.$CORE->_e(array('mjob','29')).': </li> 
			<li class="col-md-3"> <span>'.get_post_meta($post->ID,'hits',true).'</span> '.$CORE->_e(array('mjob','30')).':</li>
		
		</ul>
	
	<div class="clearfix"></div>
	
	</div>';
 
 	// RETURN OUTPUT
	return $STRING;
		
} 

	 	
	function hook_add_post_title_text($c){ global $CORE;
	return $c."".$CORE->_e(array('mjob','21'));
	}
 
	function hook_callback_process_orderid_after($obits){
	
		// CHECK IF THIS IS A DOWNLOAD PAYMENT
		if(substr($obits[0],0,2) == "MJ"){ global $wpdb;
	 
			global $userdata, $CORE, $wpdb;
			
			// CHECK WE HAVENT ALREADY DONE THIS BEFORE
			if(get_user_meta('1','done_'.$obits[1], true) != ""){ return; }
			update_user_meta('1','done_'.$obits[1], date('Y-m-d H:i:s'));
			
			
			// GET POST DATA
			$post_data = get_post($obits[1]);
			
			// DELETE ALL THE OLD WORKFLOW HISTORY
			$SQL = "DELETE FROM ".$wpdb->posts." 
			WHERE post_type = 'ppt_workflow' 
			AND post_title LIKE ('%-".$obits[1]."-reply-".$userdata->ID."%') OR post_title LIKE ('%".$userdata->ID."-".$obits[1]."%')";
			$wpdb->query($SQL);
			
			// ADD NEW WORKFLOW
			$my_post = array();
			$my_post['post_title'] 		= $obits[2]."-".$obits[1];
			$my_post['post_content'] 	= "<h3>".$CORE->_e(array('mjob','16'))."</h3><p>Date: ".hook_date(date('Y-m-d H:i:s'))." </p><p>".$CORE->_e(array('mjob','19'))."</p><p>".$CORE->_e(array('mjob','20'))."</p>";
			$my_post['post_excerpt'] 	= "";
			$my_post['post_status'] 	= "publish";
			$my_post['post_type'] 		= "ppt_workflow";
			$my_post['post_author'] 	= $obits[2];
			$POSTID 					= wp_insert_post( $my_post );
				
			// STORE POST ID
			add_post_meta($POSTID, "postID", $obits[1]);
			 
			// SETV VISIBLILTY			 
			add_post_meta($POSTID, "visible_to", array($post_data->post_author, $obits[2] ) );
			
			// payer USER DATA
			$PAYERUSER = get_user_by( 'id', $obits[2] );
			
			// LISTING USER DATA
			$THISUSER = get_user_by( 'id', $post_data->post_author );
			
			// LISTING LINK
			$LISTINGLINK = get_permalink($obits[1]);		
		
			//email the listing author with new job details
			$my_post = array();
			$my_post['post_title'] 		= $CORE->_e(array('mjob','16'));
			$my_post['post_content'] 	= 
			"<h3>".$CORE->_e(array('mjob','16'))."</h3><p>Date: ".hook_date(date('Y-m-d H:i:s'))." </p>
			<p>".$PAYERUSER->user_login." ".$CORE->_e(array('mjob','17'))."</p>
			<p><a href='".$LISTINGLINK."'>".$CORE->_e(array('mjob','18'))."</a></p>";
			
			$my_post['post_excerpt'] 	= "";
			$my_post['post_status'] 	= "publish";
			$my_post['post_type'] 		= "wlt_message";
			$my_post['post_author'] 	= 1;
			$POSTID 	= wp_insert_post( $my_post );
			
			// ADD SOME EXTRA CUSTOM FIELDS
			add_post_meta($POSTID, "username", $THISUSER->user_login );	
			add_post_meta($POSTID, "userID", $THISUSER->ID);	
			add_post_meta($POSTID, "status", "unread" );
			add_post_meta($POSTID, "ref", get_permalink($obits[1]) );
			
			// send email
			$_POST['link'] = $LISTINGLINK;
			$_POST['username'] =  $THISUSER->user_login;
			$CORE->SENDEMAIL($post_data->post_author,'mj_neworder_seller');
			$_POST['username'] =  $PAYERUSER->user_login;
		 	$CORE->SENDEMAIL($userdata->ID,'mj_neworder_buyer');
			
			
			if(isset($GLOBALS['CORE_THEME']['house_percentage']) && strlen($GLOBALS['CORE_THEME']['house_percentage']) > 0){
			  
			  	// GET PRICE FOR THE LISTING
				$SQL = "SELECT order_total FROM ".$wpdb->prefix."core_orders WHERE order_id = ('".strip_tags($obits[0]."-".$obits[1]."-".$obits[2]."-".$obits[3])."') LIMIT 1";
				 
				$hasorder = $wpdb->get_results($SQL, OBJECT);
				if(!empty($hasorder)){				
					$price = $hasorder[0]->order_total;		
				}else{				
					$price = get_post_meta($obits[1],'price',true);				
				}
			  
				// WORK OUT AMOUNT OWED BY THE SELLER
				$AMOUNTOWED = ($GLOBALS['CORE_THEME']['house_percentage']/100)*$price;
				$AMOUNTOWED = -1 * abs($AMOUNTOWED);
				 
				// DEDUCT AMOUNT FROM MEMBERS AREA
				$user_balance = get_user_meta($post_data->post_author,'wlt_usercredit',true);
				
				if($user_balance == ""){ $user_balance = 0; }
				$user_balance = $user_balance + ( -1 * abs($AMOUNTOWED) );
				 
				update_user_meta($post_data->post_author,'wlt_usercredit', $user_balance);
			 		 
			}
			
			// UPDATE SALES COUNTER
			$css = get_post_meta($obits[1],'sales_count', true);
			if($css == "" || !is_numeric($css) ){ $css = 0; }
			update_post_meta($obits[1],'sales_count',  $css + 1);
			
			// DELETE ANY HISTORY FOR THIS ITEM FROM PREVIOUS PURCHASES
			delete_post_meta($obits[1], "jobdone_".$userdata->ID);
			 
		}		
	
	}
	
	function shortcode_sales(){ global $wpdb, $post;
	
		$SQL = "SELECT count(*) AS total FROM `".$wpdb->prefix."core_orders` WHERE order_items ='".$post->ID."' LIMIT 1 "; 
		$orders = (array)$wpdb->get_results($SQL); 	
		return $orders[0]->total;
			
	}	
	
	// CUSTOM FIELDS FOR THIS THEME
	function _hook_customfields($c){ global $CORE;
	
		$o = 50;
		
		// DAYS ARRAY
		$i=2; $gg = array("1" => "1 ".$CORE->_e(array('date','1'))); 
		while($i< 31){
		$gg[$i] = $i." ".$CORE->_e(array('date','2'));
		$i++; 
		}
 		
		$c[$o]['title'] 	= $CORE->_e(array('mjob','33'));
		$c[$o]['name'] 		= "days";
		$c[$o]['type'] 		= "select";
		$c[$o]['class'] 	= "form-control";		
		$c[$o]['listvalues'] 	= $gg;
		$c[$o]['help'] 		= $CORE->_e(array('mjob','34'));
		$o++;		
	 
		$c[$o]['title'] 	= $CORE->_e(array('mjob','35'));
		$c[$o]['name'] 		= "purchase_type";
		$c[$o]['type'] 		= "select";
		$c[$o]['class'] 	= "form-control";		
		$c[$o]['listvalues'] 	= array(0 => $CORE->_e(array('mjob','36')), 1 => $CORE->_e(array('mjob','37')));
		$c[$o]['help'] 		= "Choose when we should stop taking new orders for you.";
		$o++;	
		
		$c[$o]['title'] 	= $CORE->_e(array('author','5'));
		$c[$o]['name'] 		= "price";
		$c[$o]['type'] 		= "price";
		$c[$o]['class'] 	= "form-control";
		$c[$o]['required'] 	= true;
		$o++;
 		
		$c[$o]['title'] 	= "";
		$c[$o]['name'] 		= "bought";
		$c[$o]['type'] 		= "hidden";
		$c[$o]['values'] 	= "0";
		$c[$o]['class'] 	= "form-control";
		$o++;	
		
		return $c;
	}
 
	// HOOK INTO THE EDIT LISTING PAGE
	function _extra_fields($c){	global $CORE;
	
		$list1 = array ( 			
		"tab7" => array("tab" => true, "title" => "Micro Job Data"),		 
			"price" => array("label" => "Price", "desc" => $CORE->_e(array('author','17'))  ),									
		); 	 
		
	return array_merge($c,$list1);
	}
	
	// SAVE JOB FUNCTIONALITY
	function jobs_savefunctions(){ global $post, $wpdb, $userdata, $CORE; 
 	
	if( isset($_POST['workflow_action']) ){
		switch($_POST['workflow_action']){
		
			case "releasefunds": {
			
			if(!is_numeric($_POST['workflow_pid'])){ return; }
			 
			// get the order ID
			$SQL = "SELECT autoid, order_id, order_status, order_total FROM `".$wpdb->prefix."core_orders` WHERE user_id = ('".$userdata->ID."') AND order_items = ( '".$_POST['workflow_pid']."' ) LIMIT 1 "; 
			$orders = (array)$wpdb->get_results($SQL);
		 
			if(isset($orders[0])  ){ //   && $orders[0]->order_status != 5  // issue with multple of same order
			
				// UPDATE THE ORDER STATUS
				$SQL = "UPDATE `".$wpdb->prefix."core_orders` SET order_status = 5 
				WHERE user_id = ('".$userdata->ID."') AND order_items = '".$_POST['workflow_pid']."' 
				AND autoid ='".$orders[0]->autoid."' LIMIT 1 "; 
				$wpdb->query($SQL);
			 
				// GET THIS POSTS AUTHOR
				$HH = get_post($_POST['workflow_pid']);
				
				// NOW RELEASE THE FUNDS FOR THE USER					 
				$user_balance = get_user_meta($HH->post_author,'wlt_usercredit',true);
				if($user_balance == ""){ $user_balance = 0; }
				$user_balance += $orders[0]->order_total;
				  
				// UPDATE SELLERS CREDIT
				update_user_meta($HH->post_author,'wlt_usercredit', $user_balance);
				
				// READJUST THE LISTINDG
				$datenow = date('Y-m-d H:i:s');
				update_post_meta($_POST['workflow_pid'], 'jobdone_'.$userdata->ID, $datenow); 
				update_post_meta($_POST['workflow_pid'], str_replace(" ","",$datenow)."_paid", $orders[0]->order_total); 

				// REDIRECT
				wp_redirect( get_permalink( $post->ID )."?bbid=".$_POST['bbid']."&funds=1"); 
				exit;
			
			}					
			
			
			} break;		 
		
			case "addworkflow": { 
			
				$my_post = array();
			 
				$my_post['post_title'] 		= $userdata->ID."-".$_POST['workflow_pid']."-reply-".$_POST['workflow_replid'];				 
				$my_post['post_content'] 	= strip_tags(strip_tags($_POST['workflow_message']));
				$my_post['post_excerpt'] 	= "";
				$my_post['post_status'] 	= "publish";
				$my_post['post_type'] 		= "ppt_workflow";
				$my_post['post_author'] 	= $userdata->ID;
				$POSTID 					= wp_insert_post( $my_post );
				
				// HANDLE THE FILE UPLOADS
				if ( ! function_exists( 'media_handle_upload' ) ) {
					// These files need to be included as dependencies when on the front end.
					require_once( ABSPATH . 'wp-admin/includes/image.php' );
					require_once( ABSPATH . 'wp-admin/includes/file.php' );
					require_once( ABSPATH . 'wp-admin/includes/media.php' );
				}
				
				if(!empty($_FILES['workflow_file'])){
					$attachment_id = media_handle_upload( 'workflow_file', $POSTID );					
					if ( is_wp_error( $attachment_id ) ) {
							// There was an error uploading the image.
							//die(print_r($attachment_id)."error");	
					} else {
							// The image was uploaded successfully!
							add_post_meta($POSTID, "attachmentid", $attachment_id);
					}
				}
				 
				// STORE POST ID
				add_post_meta($POSTID, "postID", $_POST['workflow_pid']);
			 	
				// IF PAGE AUTHOR IS REPLING TO OWN POST, MAKE SURE A REPLID IS SET
				if($_POST['workflow_pauthor'] == $userdata->ID){
 
					// SETV VISIBLILTY
					add_post_meta($POSTID, "visible_to", array($_POST['workflow_replid'], $userdata->ID ) );
					
					// CHECK FOR JOB DONE
					if($_POST['workflow_done'] == "1"){					
						update_post_meta($_POST['workflow_pid'], "jobdone_".$_POST['workflow_replid'], 1 );					
					}
			 
				}else{
								
					// SETV VISIBLILTY
					add_post_meta($POSTID, "visible_to", array($_POST['workflow_pauthor'], $userdata->ID ) );
				
				}
				
				// ADD MESSAGE TO USER FOR NOTIFICAION
				$my_post = array();
				$my_post['post_title'] 		= $CORE->_e(array('mjob','46'));
				$my_post['post_content'] 	= $CORE->_e(array('mjob','47'))."; <br><br><a href='".get_permalink($_POST['workflow_pid'])."?bbid=".$_POST['bbid']."' style='font-size:20px; text-decoration:underline;'>".$CORE->_e(array('mjob','48'))."</a>";
				$my_post['post_excerpt'] 	= "";
				$my_post['post_status'] 	= "publish";
				$my_post['post_type'] 		= "wlt_message";
				$my_post['post_author'] 	= $userdata->ID;
				$POSTID 					= wp_insert_post( $my_post );
				
				add_post_meta($POSTID, "username", get_the_author_meta( 'user_login', $_POST['workflow_replid'] ));	
				add_post_meta($POSTID, "userID", $_POST['workflow_replid']);
				add_post_meta($POSTID, "status", "unread");
				 
				// REDIRECT
				wp_redirect( get_permalink( $post->ID )."?bbid=".$_POST['bbid']); 
				exit;
							
			} break;
			}
		}
	}
	
	
	
	
	

	
 


 


 


 
function add_new_emails(){ global $wpdb; $wlt_emails = get_option("wlt_emails"); $core_admin_values = get_option("core_admin_values");  ?>
<hr />
<table class="table table-bordered table-striped">
            <thead>
              <tr>
                <th>MicroJobs Board Emails</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
            
            <tr><td>
<span class="label label-inverse">New Order - sent to buyer</span>
<br> <a style="font-size:11px;" href="javascript:void(0);" onclick="alert('username = (username) \n link to post (link) ');return false;">[view  shortcodes]</a>
</td>
<td>
<select data-placeholder="Choose a an email..." class="chzn-select" name="admin_values[emails][mj_neworder_buyer]">
   
    
	<?php 
	if(is_array($wlt_emails)){ 
		foreach($wlt_emails as $key=>$field){ 
			if(isset($core_admin_values['emails']) && $core_admin_values['emails']['mj_neworder_buyer'] == $key){	$sel = " selected=selected ";	}else{ $sel = ""; }
			echo "<option value='".$key."' ".$sel.">".stripslashes($field['subject'])."</option>"; 
		} 
	} 
	?> 
    
     <option value="" <?php if($core_admin_values['emails']['mj_neworder_buyer'] == ""){ echo " selected=selected "; } ?>>--- do not send --- </option>
</select> 
</td></tr> 

   
            <tr><td>
<span class="label label-inverse">New Order - sent to seller</span>
<br> <a style="font-size:11px;" href="javascript:void(0);" onclick="alert('username = (username) \n link to post (link) ');return false;">[view  shortcodes]</a>
</td>
<td>
<select data-placeholder="Choose a an email..." class="chzn-select" name="admin_values[emails][mj_neworder_seller]">
   
    
	<?php 
	if(is_array($wlt_emails)){ 
		foreach($wlt_emails as $key=>$field){ 
			if(isset($core_admin_values['emails']) && $core_admin_values['emails']['mj_neworder_seller'] == $key){	$sel = " selected=selected ";	}else{ $sel = ""; }
			echo "<option value='".$key."' ".$sel.">".stripslashes($field['subject'])."</option>"; 
		} 
	} 
	?> 
    
     <option value="" <?php if($core_admin_values['emails']['mj_neworder_seller'] == ""){ echo " selected=selected "; } ?>>--- do not send --- </option>
</select> 
</td></tr> 


<!------------ END FIELD -------------->  
  </tbody> </table>
<?php }



 
	
	//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">
         Micro Job 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">House Percentage</div> 
        
        <p>The house percantage is the amount charged to the listing author when a user purchases their job.</p>
        
        <p>Leave blank if you do not wish to collect this payment.</p>
    	
        <hr />
     
    <div class="form-row control-group row-fluid" id="myaccount_page_select">
        <label class="control-label span5" for="normal-field">House Percentage</label>
        <div class="controls span6">         
         <div class="input-prepend">
          <span class="add-on">%</span>
          <input type="text" name="admin_values[house_percentage]" value="<?php echo stripslashes($core_admin_values['house_percentage']); ?>" class="span4">
        </div>  
        <p>This is the % you will keep from sold jobs.</p>      
        </div>
    </div>
	
    
    
    </div></div></div></div>
    
    <?php
    
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
/* =============================================================================
 MENU LAYOUT FOR ACCOUNT PAGE
========================================================================== */

 
function jb_usermenu_after(){  global $wpdb, $CORE, $userdata; 

if(isset($_GET['fdid'])){ return; }

// GET ORDERS FROM DATABASE
$order_string = $this->MYORDERS(); 

// GET MY UNFINISHED ORDERS
$sales_string_incomplete = $this->MYSALES(1);
 
// GET MY FINISHED ORDERS
$sales_string_complete = $this->MYSALES(5);

?>

<!-- START ACCOUNT WIDTHDRAWAL  -->
<div class="panel panel-default" id="MyMJobs" style="display:none;">
        
<div class="panel-heading"><?php echo $CORE->_e(array('mjob','40')); ?></div>
		 
	<div class="panel-body">
      
    

      <div id="Tabs">    
     
      <ul class="nav nav-tabs" role="tablist">
      
      <li role="presentation" class="active"><a href="#t1" aria-controls="home" role="tab" data-toggle="tab"><?php echo $CORE->_e(array('order_status','title0')); ?></a></li>
      
      <li role="presentation"><a href="#t2" aria-controls="profile" role="tab" data-toggle="tab"><?php echo $CORE->_e(array('mjob','1')); ?> (<?php echo count($sales_string_incomplete); ?>)</a></li>
      
      <li role="presentation"><a href="#t3" aria-controls="profile" role="tab" data-toggle="tab"><?php echo $CORE->_e(array('mjob','38')); ?> (<?php echo count($sales_string_complete); ?>)</a></li>
 
      </ul>    
   <hr />
      <div class="tab-content">
      
            <div role="tabpanel" class="tab-pane active" id="t1">
            
            <?php if(strlen($order_string) > 1 ){ ?>            
                     
                    <ul class="list-group"> 
                  
                    <?php  echo $order_string;  ?> 
                       
                    </ul>
               
            <?php }else{ ?>
            
            	<h4 class="text-center"><?php echo $CORE->_e(array('gallerypage','24')); ?></h4>
            
            <?php } ?>              
            
            </div>
            <div role="tabpanel" class="tab-pane" id="t2">            
              	
                <?php if(!empty($sales_string_incomplete)){ ?>
                
                <ul class="list-group">
                                
                <?php foreach($sales_string_incomplete as $dd){ echo $dd; } ?> 
                
                </ul>
                
            <?php }else{ ?>
            
            	<h4 class="text-center"><?php echo $CORE->_e(array('gallerypage','24')); ?></h4>
            
            <?php } ?> 
            
            </div>
            
            
            <div role="tabpanel" class="tab-pane" id="t3">
             
                <?php if(!empty($sales_string_complete)){ ?>
                
                <ul class="list-group">
                                
                <?php foreach($sales_string_complete as $dd){ echo $dd; } ?> 
                
                </ul>
                
            <?php }else{ ?>
            
            	<h4 class="text-center"><?php echo $CORE->_e(array('gallerypage','24')); ?></h4>
            
            <?php } ?> 
            
            </div>
      
      </div> 
      
      </div>
      
      <hr />
        		 
	  <button class="btn btn-default pull-right" type="button" onclick="jQuery('#MyAccountBlock').show();jQuery('#MyMJobs').hide();"><?php echo $CORE->_e(array('button','7')); ?></button>
		
      <div class="clearfix"></div>
      
      </div>

</div>
         
<?php  
}	
	
	
/* =============================================================================
 ORDER CLASS
========================================================================== */

function MYSALES($status=1){

global $CORE, $userdata, $wpdb; $output = array();

$SQL = "SELECT ".$wpdb->prefix."core_orders.*, ".$wpdb->prefix."posts.ID, ".$wpdb->prefix."posts.post_title FROM ".$wpdb->prefix."core_orders, ".$wpdb->prefix."posts
WHERE ".$wpdb->prefix."posts.ID = ".$wpdb->prefix."core_orders.order_items 
AND ".$wpdb->prefix."posts.post_author = ('".$userdata->ID."') 
AND ".$wpdb->prefix."core_orders.order_status = ".$status." 
ORDER BY ".$wpdb->prefix."core_orders.order_date DESC "; 
$orders = (array)$wpdb->get_results($SQL);

if(!empty($orders)){ foreach($orders as $order){

ob_start();
?>
 

<li class="list-group-item">

<?php echo $CORE->GETIMAGE($order->ID); ?>

<a href="<?php echo get_permalink($order->ID); ?>?wf=1" class="btn btn-primary pull-right"><?php echo $CORE->_e(array('mjob','2')); ?></a>
	<h4><?php echo $order->post_title; ?></h4>   
    <span><?php echo hook_order_status($CORE->ORDER_STATUS($order->order_status)); ?></span>
	<hr style="margin-top:5px; "/>
    <ul class="list-inline">
        <li><?php echo $CORE->_e(array('checkout','4')); ?>: <?php echo hook_price($order->order_total); ?></li>
        <li><?php echo $CORE->_e(array('feedback','23')); ?>: <?php echo hook_date($order->order_date." ".$order->order_time); ?></li>
        <li><?php echo $CORE->_e(array('login','10')); ?>: <a href="<?php echo get_author_posts_url( $order->user_id, get_the_author_meta( 'user_nicename', $order->user_id ) ); ?>"><?php echo get_the_author_meta( 'display_name', $order->user_id ); ?></a></li>
        <li>ID: <?php echo $order->order_id; ?> </li>
    </ul>         
	<div class="clearfix"></div>
</li>
<?php
$output[]= ob_get_clean(); 
} }

return $output;

}

function MYORDERS(){ global $CORE, $userdata, $wpdb; $STRING = ""; $i=1; 

$SQL = "SELECT * FROM `".$wpdb->prefix."core_orders` WHERE user_id = ('".$userdata->ID."') "; 
$orders = (array)$wpdb->get_results($SQL);
if(!empty($orders)){
	foreach($orders as $order){ 
	
	// order bits
	$obits = explode("-",$order->order_id);
	
	// IMAGE
	$image = hook_image_display(get_the_post_thumbnail($obits[1], 'thumbnail', array('class'=> "wlt_thumbnail img-responisve")));
	if($image == ""){
	$image = $this->FALLBACK_IMAGE($obits[1]);
	}
	
	$STRING .= "<li class='list-group-item'>
 	
	<div class='col-md-2'>
	
	<a href='".get_permalink($obits[1])."' class='frame'>".$image."</a> 
	
	</div>
	
	<div class='col-md-10'>
	
	<h4 style='margin-top:10px;'><a href='".get_permalink($obits[1])."'>".get_the_title($obits[1])."</a></h4>
			  
	<p>".$CORE->_e(array('order_status','title2')).": ".hook_date($order->order_date)." </p>";
	
	$STRING .= hook_price($order->order_total)." <span>(".hook_order_status($CORE->ORDER_STATUS($order->order_status)).")</span> | ";
	
	// CHECK IF WAITING FOR FUNDS TO BE RELEASED
				  
	$STRING .= "<i class='fa fa-file-excel-o'></i> <a href='".get_template_directory_uri()."/_invoice.php?invoiceid=".$order->autoid."' target='_blank' style='text-decoration:underline;'>".$CORE->_e(array('mjob','4'))."</a> ";
					  
	if($order->order_status != 5){
	
	$STRING .= "<a href='".get_permalink($obits[1])."?viewprogress=1' class='btn btn-primary right' style='margin-left:10px;'>".$CORE->_e(array('mjob','3'))."</a>";
	
	}					  
					  
	$STRING .= "</div>
	<div class='clearfix'></div>			  
	</li>"; 
	 
	$i++;
	} // end foreach
	
	return $STRING;
} // end if
return $STRING;

}



















/* =============================================================================
WORKFLOW FUNCTION
========================================================================== */

function shortcode_workflow(){ global $CORE, $wpdb, $post, $userdata; $STRING = ""; 

$returnE = "<script>jQuery(document).ready(function(){ jQuery('#Tabs .nav').hide(); }); </script>";

// WORKFLOW FOR MICROJOBS
$canShowWorkflow = false;

if(!$userdata->ID){

	$canShowWorkflow = false;

}elseif($userdata->ID == $post->post_author){
	
	$canShowWorkflow = true;
		
}else{	

	// WORKFLOW IS ONLY VISIBLE FOR USERS WHO HAVE BOUGHT THIS LISTING
	$SQL = "SELECT count(*) AS found FROM `".$wpdb->prefix."core_orders` WHERE order_id LIKE ('%-".$post->ID."-%') AND user_id = '".$userdata->ID."' LIMIT 1"; 
	$forder = $wpdb->get_results($SQL, OBJECT);
	if($forder[0]->found > 0){
		$canShowWorkflow = true;
	}	
}


if(!$canShowWorkflow){ return $returnE; }

// SHOW TAB
$STRING = "<script>jQuery(document).ready(function(){ jQuery('#Tabs a[href=\"#t3\"]').tab('show'); }); </script>";


// FIND EXISTING PROPOSALS
$OUTPUTDATA = array();
$postslist = query_posts('post_type=ppt_workflow&meta_key=postID&meta_value='.$post->ID,"&posts_per_page=100");
if(!empty($postslist)){

	// GET POST AUTHOR DATA
	$author_user = get_user_by('id', $post->post_author);
 	
	foreach ($postslist as $pro){
 
	
	// CHECK FOR ATATCHMENT
	$attachmentid = get_post_meta($pro->ID, "attachmentid", true);
	$file = "";
	if(strlen($attachmentid) > 2){			
		$file = wp_get_attachment_url( $attachmentid );
	}		
			
	 // SKIP UNLESS IS THE BIDDER OR THE POST AUTHOR
	 if(!in_array($userdata->ID, get_post_meta($pro->ID, "visible_to", true)) ){ continue;  }
	 
 	 // GET USER DATA
	 $user = get_user_by('id', $pro->post_author);
	
		// SETUP AUTHORS
		if($pro->post_author != $post->post_author){
		 
			// CHECK FOR JOB DONE
			$jobdone = get_post_meta($post->ID, "jobdone_".$pro->post_author, true);
			 	  
			if(substr($jobdone,0,4) == date('Y') ){			
				$status = 2; // PAID AND RELEASED				
			}elseif($jobdone == 1){				
				$status = 1; // JOB COMPLETED BY NOT RELEASED				
			}else{
				$status = 0; 
			}
			
			$OUTPUTDATA[$pro->post_author]['name'] = $user->user_login;
			$OUTPUTDATA[$pro->post_author]['userid'] = $user->ID;
			$OUTPUTDATA[$pro->post_author]['status'] = $status;	
			$OUTPUTDATA[$pro->post_author]['file'] = $post->ID;
			if($status == 2){
			$OUTPUTDATA[$pro->post_author]['completed'] = hook_date($jobdone);
			}		
			$OUTPUTDATA[$pro->post_author]['comment'][] = array("userid" => $user->ID, "file" => $file, "message" => 	wpautop($pro->post_content), "user" => $user->user_login, "photo" => get_avatar($user->ID, 100 ) );		 
			
		}else{
		
			$VISIBLETO = get_post_meta($pro->ID, "visible_to", true);
			$OUTPUTDATA[$VISIBLETO[0]]['comment'][] = array("userid" => $post->post_author, "file" => $file, "message" => 	wpautop($pro->post_content),  "user" => $author_user->user_login, "photo" => get_avatar($author_user->ID, 100 ));
		}
	
	
	}
}
wp_reset_query();

// HIDE IF EMPTY
if(empty($OUTPUTDATA)){ return $returnE; }


// BUILD THE OUTPUT
 
$STRING .= '<a name="workflow"></a>';
 
if($post->post_author == $userdata->ID){ $ss .= "style='display:none;'"; }else{ $ss = ""; } 

 if(isset($_GET['bbid']) && is_numeric($_GET['bbid']) ){ $dbbid = $_GET['bbid']; }else{  $dbbid = ""; }
 
$STRING .= '<form method="post" id="workflow_msgbox" action="'.get_permalink($post->ID).'" '.$ss.' enctype="multipart/form-data" > 
<input type="hidden" name="workflow_action" value="addworkflow"> 
<input type="hidden" name="workflow_pid" value="'.$post->ID.'">
<input type="hidden" name="workflow_pauthor" value="'.$post->post_author.'"> 
<input type="hidden" name="workflow_replid" id="workflow_replid" value="">
<input type="hidden" name="bbid" id="bbid" value="'.$dbbid.'">
<h4>'.$CORE->_e(array('mjob','13')).' <span class="required">*</span></h4>
<p><textarea rows="3" style="width:98%;" name="workflow_message" id="workflow_message" tabindex="55" class="form-control"></textarea></p>

<input type=file name="workflow_file" id="workflow_file">

<hr />
';
     
    
if($post->post_author == $userdata->ID){ 
$STRING .= '<h4>'.$CORE->_e(array('mjob','12')).'</h4>
        <p>'.$CORE->_e(array('mjob','11')).'</p>	 
        <input name="workflow_done" type="checkbox" value="1" /> '.$CORE->_e(array('mjob','10')).'	
        <hr />';
}
     
$STRING .= '<div class="clearfix"></div><button class="btn btn-success btn-lg" style="submit">'.$CORE->_e(array('mjob','9')).'</button><hr />
    
</form>

<div class="panel-group" id="workflowlist">';

$i=1; foreach($OUTPUTDATA as $key => $display){
  
  $STRING .= '<div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">';
	  
	  if(isset($display['completed']) && $post->post_author != $userdata->ID  ){
			
            $STRING .= '<div class="pull-right"> <a href="'.$GLOBALS['CORE_THEME']['links']['myaccount']."?fdid=".$post->ID.'" class="label label-success">'.$CORE->_e(array('feedback','1')).'</a></div>';
		
	}elseif(isset($display['completed']) && $post->post_author == $userdata->ID ){
	
	$STRING .='<span class="pull-right label label-warning">'. $CORE->_e(array('order_status','5')).'</span>';
			
	}
	  
      		$STRING .=  '<a data-toggle="collapse" data-parent="#workflowlist" href="#b'.$i.'" onclick="jQuery(\'#bbid\').val(\''.$i.'\');"> <i class="fa fa-sort-down" style="float:left; font-size:30px; margin-right:20px; margin-top:-15px;"></i>';
        	
            if($status == 0 ){ 
			
            $STRING .='<span class="pull-right label label-success">'. $CORE->_e(array('mjob','7')).'</span>';
			
            }elseif($status == 1){
			
			$STRING .='<span class="pull-right label label-info">'. $CORE->_e(array('mjob','6')).'</span>';
			
			}
            
           $STRING .= '<b>'. $display['name'].'</b> - '.count($display['comment']).' '. $CORE->_e(array('single','37')).'. 
        </a>
      </h4>';
	  
	  if(isset($display['completed'])){
	  
	  $STRING .= ' <small>'.$CORE->_e(array('mjob','8')).' '.$display['completed'].'</small>';
	  }
	  
   $STRING .= ' </div>
    <div id="b'.$i.'" class="panel-collapse collapse">
      <div class="panel-body">';
	  
	  $replybtn = false;
      
      foreach($display['comment'] as $cdata){
      
      $STRING .= '<div class="thumbnail">
      <div class="pull-right">'.$cdata['photo'].'</div>
      <p class="says">'.$cdata['user'].' '.$CORE->_e(array('author','26')).'</p>
      <div class="msg">'.$cdata['message'].'</div>';
	  
	  // FILE ATTACHMENT	  
	  if(strlen($cdata['file']) > 2){
	  $STRING .= '<div class="file"> <i class="fa fa-file-picture-o"></i> <a href="'.$cdata['file'].'" style="text-decoration:underline" target="_blank"> '.$CORE->_e(array('mjob','42')).' </a> </div>';
	  }
	  
      $STRING .= '<div class="clearfix"></div>
      </div> '; 
	   
	  if($display['status'] == 1 && $post->post_author != $userdata->ID && $cdata['userid'] != $userdata->ID && !isset($jobdoneset) ){ $jobdoneset = true; 
 			
	$STRING .= '<form method="post" id="workflow_msgbox" action="'.get_permalink($post->ID).'"> 
			<input type="hidden" name="workflow_action" value="releasefunds"> 			
			<input type="hidden" name="workflow_pid" value="'.$post->ID.'">
			<input type="hidden" name="bbid" id="bbid" value="'.$i.'">
			<button class="btn btn-lg btn-success pull-right" type="submit"> '.$CORE->_e(array('mjob','6')).' </button> 
			
			</form>';
			 
		}
            
      
		if($display['status'] != 2 && $cdata['userid'] != $userdata->ID && !$replybtn  ){ 
                    
             $STRING .= '<a href="#top" onclick="jQuery(\'#workflow_replid\').val(\''. $key.'\');jQuery(\'#workflow_msgbox\').show(); jQuery(\'#bbid\').val(\''.$i.'\');" class="btn btn-primary">'.$CORE->_e(array('mjob','5')).'</a>';  $replybtn = true;
                        
        }
			             
      $STRING .= '<hr />';
	 
      }               
        
      $STRING .= '</div>    </div>  </div>';
	  
$i++; }


$STRING .= '</div></div>';

return $STRING;

} // END WORKFLOW FUNC







/* =============================================================================
ADD-ONS FUNCTION
========================================================================== */

function _hook_add_listtitles($c){ 
$c[7] = array("title" => "Add-ons");
return $c;
}
function _hook_add_listdata($c){ global $CORE;

if($c == 7){
?>
<a href="javascript:void(0);" onClick="jQuery('#wlt_customextras_list_fields').clone().appendTo('#wlt_customextras_list');" class="btn btn-success"><?php echo $CORE->_e(array('mjob','22')); ?></a>

<hr />         
             
<ul id="wlt_customextras_list" class="list-group">

<?php $current_data = get_post_meta($_GET['eid'],'customextras', true); if(is_array($current_data)){ $i=0; foreach($current_data['name'] as $data){ if($current_data['name'][$i] !=""){ ?>
<li class="list-group-item" id="ff<?php echo $i; ?>"> 
  
    <div class="inside">
    
        <p class="control-label"><?php echo $CORE->_e(array('mjob','23')); ?></p>
        
        <input type="text" name="customextras[name][]" id="ff<?php echo $i; ?>_title" value="<?php echo $current_data['name'][$i]; ?>" class="form-control"  />  
         <br />
        <p class="control-label"><?php echo $CORE->_e(array('mjob','24')); ?></p>
        
        <textarea name="customextras[value][]" class="form-control" style="width:100%;height:100px;"><?php echo trim($current_data['value'][$i]); ?></textarea>  
       
       	 <br />
 		<p class="control-label"><?php echo $CORE->_e(array('mjob','25')); ?></p>
        
        <div class="field_wrapper"><div class="input-group col-md-4">
			<input type="text" name="customextras[price][]" maxlength="255" class="form-control" value="<?php echo $current_data['price'][$i]; ?>" >
			<span class="input-group-addon"><?php echo $GLOBALS['CORE_THEME']['currency']['code']; ?></span></div>
        </div>
       
        <a href="javascript:void(0);" onClick="jQuery('#ff<?php echo $i; ?>_title').val('');jQuery('#ff<?php echo $i; ?>').hide();" class="btn btn-warning pull-right"><?php echo $CORE->_e(array('button','3')); ?></a>
        <div class="clearfix"></div>
    </div>    
    
</li>
<?php } $i++; } } ?>

</ul>

<div style="display:none"><div id="wlt_customextras_list_fields">
    <li class="list-group-item"> 
 
    <div class="inside">    
       
        <p class="control-label"><?php echo $CORE->_e(array('mjob','23')); ?></p>
        
        <input type="text" name="customextras[name][]" value="" class="form-control"  />  
        
         <br />
        <p class="control-label"><?php echo $CORE->_e(array('mjob','24')); ?></p>
        
        <textarea name="customextras[value][]" class="form-control" style="width:100%;height:100px;"></textarea>  
         <br />
 		<p class="control-label"><?php echo $CORE->_e(array('mjob','25')); ?></p>
        
        <div class="field_wrapper"><div class="input-group col-md-4">
			<input type="text" name="customextras[price][]" maxlength="255" class="form-control" >
			<span class="input-group-addon"><?php echo $GLOBALS['CORE_THEME']['currency']['code']; ?></span></div>
        </div>
            
    </div>
    </li>    
</div></div>
 
<?php
}

}



	
 
}

?>