<?php
// Module to manage bidders


// helper functions

function wpa_getnumberofbidders( $auction_id ) {
  global $wpdb;	

	$table_name = $wpdb->prefix . "wpa_bidderrequests";
  $strSQL = "SELECT count(*) FROM $table_name WHERE auction_id = $auction_id  AND RTB_Status = ".RTB_approved;
  $number = $wpdb->get_var($strSQL);
  
  return intval($number);

}

add_action('wp_ajax_manage_bidders_data_save', 'manage_bidders_save_ajax');
add_action('wp_ajax_manage_bidders_data_change', 'manage_bidders_change_ajax');
add_action('wp_ajax_manage_bidders_settings_change', 'manage_settings_change_ajax');
add_action('wp_ajax_clear_expired_bidders', 'clear_expired_bidders_ajax');

function manage_settings_change_ajax() {

  $button = $_POST['button'];

  if ( $button != "" ) 
    update_option('wp_auctions_autoapprove', $button);
  
  die("done");
}

function clear_expired_bidders_ajax() {

  global $wpdb;
	$table_name = $wpdb->prefix . "wpa_bidderrequests";
  $sub_table_name = $wpdb->prefix . "wpa_auctions";
    
  $strSQL = "DELETE From $table_name WHERE auction_id in (SELECT id FROM $sub_table_name WHERE '".current_time('mysql',"1")."' >= date_end)";
  $result = $wpdb->query($strSQL);
  
  die("done = $strSQL");
}

function manage_bidders_change_ajax() {

  global $wpdb;	
  $options = get_option('wp_auctions');
  $title = $options['title'];
  $currencycode = $options['currencycode'];
  $landingpage = $options['landingpage'];
  if ($landingpage == "") $landingpage = get_option('siteurl');
  
  $id = $_POST['id'];
  $state = $_POST['state'];

	$table_name = $wpdb->prefix . "wpa_bidderrequests";
  $sql = "UPDATE $table_name SET RTB_Status=$state WHERE id=$id;";
  $result = $wpdb->query($sql);
 
  // send out notification if needed
  if ($state == RTB_approved) {

     $emailoptions = get_option('wp_auctions_email');

     $table_name = $wpdb->prefix . "wpa_bidderrequests";
     $strSQL = "SELECT * FROM $table_name WHERE id=".$id;
     $bidder_row = $wpdb->get_row ($strSQL);

     $auction_id = $bidder_row->auction_id;
     $bidder_id = $bidder_row->bidder_id;

     $user_info = get_userdata($bidder_id);        
     $user_email = $user_info->user_email;

     //pull in auction details
     $table_name = $wpdb->prefix . "wpa_auctions";
     $strSQL = "SELECT id, staticpage, name,description,current_price,date_create,date_end,start_price,image_url FROM $table_name WHERE id=".$auction_id;
     $rows = $wpdb->get_row ($strSQL);
     $staticpage = $rows->staticpage;
     $thisbid = $rows->current_price;

     $to      = $user_email;
     $subject = "[".$title."] ".__('You have been cleared to bid on','wpauctions') . " " . $rows->name;

     if ($emailoptions["cleartobid"] == "") {
        $body   = "You have just been cleared to bid for an auction on {site_name}\n\n";
        $body  .= "You have now been cleared to bid on the following auction: {auction_name} which is currently going at {current_price}. ";
        $body  .= "Click the link below to submit a bid.";
        $body 	.= "\n\nLink: {auction_link}";         
        $body 	.= "\n\n--------------------------------------------\n";
     } else {
        $body = $emailoptions["cleartobid"];
        
        // clean up CRLFs
        $body = str_replace("\r\n", "\n", $body);
     }				
     // prepare link
     if (strlen($staticpage) > 0) {
       $link 	= $staticpage."?auction_id=".$auction_id;         
     } else {
       $link 	= $landingpage."?auction_to_show=".$auction_id;
     } 

     // replace keywords
     $body = str_replace ( "{site_name}", get_option('blogname') , $body );
     $body = str_replace ( "{auction_name}", $rows->name , $body );
     $body = str_replace ( "{auction_link}", $link , $body );
     $body = str_replace ( "{current_price}", $currencycode.number_format($thisbid, 2, '.', ','), $body );
    
     // Send the email.
     UTF8_mail($to,$subject,$body);  
  }
  
  die("done");
}

function manage_bidders_save_ajax() {

  global $wpdb;	
	check_ajax_referer('manage_bidders', 'security');

	$status_filter = $_POST['filter_type'];
	$auction_filter = $_POST['auction_id'];
	$bidder_filter = $_POST['bidder_id'];

  $whereclause = "";
  if ($status_filter > 0) {
     $whereclause = " AND RTB_Status = ".$status_filter;
  }
  if ($auction_filter > 0) {
     $whereclause = " AND auction_id = ".$auction_filter;
  }
  if ($bidder_filter > 0) {
     $whereclause = " AND bidder_id = ".$bidder_filter;
  }

	$table_name = $wpdb->prefix . "wpa_bidderrequests";
	$table_name2 = $wpdb->prefix . "wpa_auctions";

	
  $strSQL = "SELECT $table_name.id, $table_name.auction_id, $table_name.bidder_id, $table_name2.name, RTB_Status FROM $table_name, $table_name2 WHERE $table_name.auction_id = $table_name2.id $whereclause";
  $rows = $wpdb->get_results ($strSQL);
  
  $results = '<table class="widefat">';
  $results .= "<tr><th>".__('Auction ID','wpauctions')."</th><th>".__('Auction Name','wpauctions')."</th><th>".__('Bidder ID','wpauctions')."</th><th>".__('Bidder Name','wpauctions')."</th><th>".__('Status','wpauctions')."</th><th>".__('Actions','wpauctions')."</th></tr>";
  foreach ( $rows as $row ) 
  {
    $results .= "<tr><td>";
	  $results .= $row->auction_id;
    $results .= "</td><td>";
	  $results .= $row->name;
    $results .= "</td><td>";
	  $results .= $row->bidder_id;
    $results .= "</td><td>";
    
    $user_info = get_userdata($row->bidder_id);        
    $results .= $user_info->user_login . " (".$user_info->user_email.")";
    
    $results .= "</td><td>";

    switch ($row->RTB_Status) {
        case RTB_requested:
            $results .= __('Requested','wpauctions');
            break;
        case RTB_approved:
            $results .= __('Approved','wpauctions');
            break;
        case RTB_denied:
            $results .= __('Denied','wpauctions');
            break;
        default:
            $results .= __('Not Assigned','wpauctions');
    }

    $results .= "</td><td>";
    $results .= "<a href='#' onClick='changeBidderState(".$row->id.",".RTB_approved." )'>".__('Approve','wpauctions')."</a>";
  	$results .= " / ";
    $results .= "<a href='#' onClick='changeBidderState(".$row->id.",".RTB_denied." )'>".__('Deny','wpauctions')."</a>";
    $results .= "</td><tr>";
  }
  $results .= "</table>";

  die ($results);
}

function wp_manage_bidders_head() {
?>
	


<?php    
}

function wp_manage_bidders() {

   global $wpdb;
   $options = get_option('wp_auctions');
	 $requesttobid = $options['requesttobid'];

   $autoapprove = get_option('wp_auctions_autoapprove');
	 if ($autoapprove == "") {
      $autoapprove = "off";
      update_option('wp_auctions_autoapprove', $autoapprove);
   }
	 
	/* if ($requesttobid != "Yes") {
    echo "This option has not been activated";
	  return;
	 }*/

   // prepare data
	$table_name = $wpdb->prefix . "wpa_auctions";
	$strSQL = "SELECT id, name, BIN_price FROM $table_name WHERE '".current_time('mysql',"1")."' < date_end ORDER BY date_end DESC";
	$auction_rows = $wpdb->get_results ($strSQL);

  $user_rows = $wpdb->get_results("SELECT ID, display_name FROM $wpdb->users ORDER BY ID");

?>
	<link rel='stylesheet' id='google-fonts-1-css'  href='https://fonts.googleapis.com/css?family=Lexend+Deca%3A100%2C100italic%2C200%2C200italic%2C300%2C300italic%2C400%2C400italic%2C500%2C500italic%2C600%2C600italic%2C700%2C700italic%2C800%2C800italic%2C900%2C900italic&#038;display=auto&#038;ver=27b5f4f630b2f9b7342f325155086c2c' media='all' />

<style>

#container{background:#ebebeb;}

.switch{
	border:none;
	background:left no-repeat;
	width:105px;
	height:46px;
	padding:0;
	margin:0;
}

.on, .off{
	width:50px;
	height:40px;
	display:inline-block;
	cursor:pointer;
}

.result{display:none; margin-top:5px; font-size:14px; color:#333;}
.result span{color:#C03; font-weight:700;}

</style>

    <script type="text/javascript">
	jQuery(document).ready(function($) {

    refreshBidders();

	  jQuery('form#manage_bidders').submit(function() {
		  refreshBidders();
		  return false;
	  });
	  
	});
		
	function refreshBidders() {
  	// get values from search line
  	var data = {};
    jQuery.each(jQuery('form#manage_bidders').serializeArray(), function(i, field) {
       data[field.name] = field.value;
    });
    jQuery.post(ajaxurl, data, function(response) {
      if(response != "Error") {
        jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-records"><p><strong><?php _e('Records refreshed.','wpauctions'); ?></strong></p></div>').show();
        t = setTimeout('fade_message()', 2000);
        jQuery('#results').html(response);
      } else {
        jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-error"><p><strong><?php _e('Hmm .. something went wrong.','wpauctions'); ?></strong></p></div>').show();
        t = setTimeout('fade_message()', 2000);
      }
    });	
	}	
		
	function fade_message() {
		jQuery('#messages').fadeOut(1000);	
		clearTimeout(t);
	}

  function changeBidderState( id, newstate ) {
     data = "id="+id+"&state="+newstate+"&action=manage_bidders_data_change";
		  jQuery.post(ajaxurl, data, function(response) {
			  if(response != "Error") {
			    jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-updated"><p><strong><?php _e('Updated.','wpauctions'); ?></strong></p></div>').show();
				  t = setTimeout('fade_message()', 2000);
			  } else {
			    jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-error"><p><strong><?php _e('Hmm .. something went wrong.','wpauctions'); ?></strong></p></div>').show();
				  t = setTimeout('fade_message()', 2000);
			  }
		  });
		  refreshBidders();
		  
		  return false;     
  }

  function clearExpiredBidders() {
     data = "action=clear_expired_bidders";
		  jQuery.post(ajaxurl, data, function(response) {
			  if(response != "Error") {
			    jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-updated"><p><strong><?php _e('Updated.','wpauctions'); ?></strong></p></div>').show();
				  t = setTimeout('fade_message()', 2000);
			  } else {
			    jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-error"><p><strong><?php _e('Hmm .. something went wrong.','wpauctions'); ?></strong></p></div>').show();
				  t = setTimeout('fade_message()', 2000);
			  }
		  });
		  refreshBidders();
		  
		  return false;     
  }

  // code for switch
  jQuery(document).ready(function(){

    jQuery('.switch').css('background', 'url("../wp-content/plugins/wp-auctions/requisites/switch.png")');
    jQuery('.on_off').css('display','none');
    jQuery('.on, .off').css('text-indent','-10000px');

    // set initial value 
    button = jQuery("input[name=auto_approve_on_off]:checked").val();
    if (button == 'off') { jQuery('.switch').css('background-position', 'right'); }
    if (button == 'on'){ jQuery('.switch').css('background-position', 'left'); }	 

      jQuery("input[name=auto_approve_on_off]").change(function() {
         var button = jQuery(this).val();
      
         if(button == 'off'){ jQuery('.switch').css('background-position', 'right'); }
         if(button == 'on'){ jQuery('.switch').css('background-position', 'left'); }	 

         data = "button="+button+"&action=manage_bidders_settings_change";
         jQuery.post(ajaxurl, data, function(response) {
           if(response != "Error") {
             jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-setting"><p><strong><?php _e('Setting Updated.','wpauctions'); ?></strong></p></div>').show();
             t = setTimeout('fade_message()', 2000);
           } else {
             jQuery('#messages').html('<div id="message" class="updated fade wpa-rtb-error"><p><strong><?php _e('Hmm .. something went wrong.','wpauctions'); ?></strong></p></div>').show();
             t = setTimeout('fade_message()', 2000);
           }
         });
        
     });

  });
</script>

<link href="../wp-content/plugins/wp-auctions/requisites/style.css" rel="stylesheet" type="text/css" />
<div class="wrap manage-bidders wp-auctions">

	<div class="clearfix">
   <div class="wpa-manage-right">
   <!--
    <input type="button" value="<?php _e('Clear Expired Bidders','wpauctions') ?>" onclick="clearExpiredBidders()" class="button" />
   </div>  
   <div class="wpa-manage-left">-->
    <form action="" name="manage_bidders" id="manage_bidders" style="display:inline">
	<div class="rfloat">
    	 <span class="submit newselect moreright"><?php _e('Status','wpauctions') ?>: 
        <select name="filter_type" onChange="refreshBidders()">
           <option value="0"><?php _e('All','wpauctions') ?></option>
           <option value="1"><?php _e('Requested','wpauctions') ?></option>
           <option value="2"><?php _e('Approved','wpauctions') ?></option>
           <option value="3"><?php _e('Denied','wpauctions') ?></option>           
        </select>

		 
Auction: 

        <select name="auction_id" onChange="refreshBidders()">
           <option value="0"><?php _e('All','wpauctions') ?></option>
<?php
            foreach ($auction_rows as $row) {
              echo '<option value="'.$row->id.'">'.$row->name.'</option>';
            }
?>
        </select>

    	 
User: 

        <select name="bidder_id" onChange="refreshBidders()">
           <option value="0"><?php _e('All','wpauctions') ?></option>
<?php
            foreach ($user_rows as $row) {
              echo '<option value="'.$row->ID.'">'.$row->display_name.'</option>';
            }
?>
        </select>
    	 
        <input type="hidden" name="action" value="manage_bidders_data_save" />
        <input type="hidden" name="security" value="<?php echo wp_create_nonce('manage_bidders'); ?>" />
        <input type="submit" value="<?php _e('Refresh','wpauctions') ?>" />
    </form>
	<input type="button" style="display:inline" value="<?php _e('Clear Expired Bidders','wpauctions') ?>" onclick="clearExpiredBidders()" />
	</span>
   </div>
   </div>
   </div><!-- Clearfix -->
   
	<h2 class="manage"><em><?php _e('Manage Bidders','wpauctions'); ?></em></h2>
    <div id="messages"></div>
    
    <div id="results"></div>
    
    <h2 class="manage" style="margin-top:1.5em;"><em><?php _e('Bidder Management Settings','wpauctions') ?></em></h2>    

    <table width="100%" cellspacing="2" cellpadding="5" class="widefat dark">

<tr valign="top" class="alternate">
  <th scope="row" class='row-title'><?php _e('Auto Approve','wpauctions'); ?></th>
  <td class='desc lesspadd' style="border-bottom: 0;">
  <form action="" id="global_settings" name="global_settings">
    <p><?php _e('Click the button below to turn Auto Approval of all registered bidders to ON (&#10003;) or OFF (&#10005;).','wpauctions'); ?></p>
	  <p><?php _e("Turning it ON will enable all users to bid automatically once they've requested access to bid. You can still Approve/Deny them above later on.",'wpauctions'); ?></p>
    <fieldset class="switch">
        <label class="off">Off<input type="radio" class="on_off" name="auto_approve_on_off" value="off"<?php if ($autoapprove == "off") echo ' checked="checked"'; ?>/></label>
        <label class="on">On<input type="radio" class="on_off" name="auto_approve_on_off" value="on"<?php if ($autoapprove == "on") echo ' checked="checked"'; ?>/></label>
    </fieldset>

    </form>
           </td>
</tr>

	

</div>

<?php	

}

?>