<?php
//---------------------------------------------------
//--------------AJAX CALLPOINTS----------------------
//---------------------------------------------------

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['requesttobid'])):

  // check security
  check_ajax_referer( "WPA-nonce" );

	// process posted values here
	$auction_id = intval($_POST['auction_id']);
	$bidder_id = intval($_POST['bidder_id']);

  $autoapprove = get_option('wp_auctions_autoapprove');

  if ($auction_id > 0 && $bidder_id > 0) {
  
  	 // check if we already have an entry like this
     $table_name = $wpdb->prefix . "wpa_bidderrequests";
  	 $strSQL = "SELECT * FROM $table_name WHERE auction_id=$auction_id and bidder_id=$bidder_id";
  	 $row = $wpdb->get_row ($strSQL);  

     if ($row == null) {
      $valuetoassign = RTB_requested;
      if ($autoapprove == "on") {
        $valuetoassign = RTB_approved;
      }
  
      $sql = "INSERT INTO ".$table_name." (id, auction_id, bidder_id, RTB_Status) VALUES (NULL, ".$auction_id.", '".$bidder_id."',  ".$valuetoassign." );";
      $result = $wpdb->query($sql);
      
      if ($result) {
       $return = __("Access to this auction has been requested",'wpauctions');
      } else {
       $return = __("Error while requesting access",'wpauctions');      
     }
    } else {
       $return = __("Access already requested",'wpauctions');          
    }
  } else {    
     $return =  "Incorrect parameters: auction_id = $auction_id / bidder_id = $bidder_id";
  }
	
	echo $return;
	exit;
	
endif;


if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['form_save'])):

  $form_data = isset($_POST['frmb']) ? $_POST : false;
  $form = new Formbuilder($form_data);
  $for_db = $form->get_encoded_form_array();

  $table_name = $wpdb->prefix . "wpa_auctiontemplates";

  if($for_db['form_id']){
    $sql = "UPDATE $table_name SET postdesc = '".$for_db['form_structure']."' WHERE id=" . $for_db['form_id'];
	} else {
		$sql = "INSERT INTO $table_name (id, templatename, postdesc) VALUES (NULL, 'that', '".$for_db['form_structure']."' );";
  }

  $result = $wpdb->query($sql);

  // exit so we don't have to take additional load
  exit;

endif;

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['form_load'])):

  $form = isset($_GET['form_id']) ? $_GET['form_id'] : false;
  if ($form) {
  	$table_name = $wpdb->prefix . "wpa_auctiontemplates";
  	$strSQL = "SELECT * FROM $table_name WHERE id=".$form;
  	$row = $wpdb->get_row ($strSQL);
  	$data = Array( 'form_id'=> $form, 'form_structure' => $row->postdesc);
  	
    $form = new Formbuilder( $data );
    $form->render_json();
  }  
  
  // exit so we don't have to take additional load
  exit;
  
endif;

// note page layout, popup and new layout all use seperate code. This reduced coupling is intentional so we can depracate as needed

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['update_newlayout'])):

  global $wpdb;

  $options = get_option('wp_auctions');
  $anonymizebidder = $options['anonymizebidder'];
  $engine = $options['engine'];
  $currencysymbol = $options['currencysymbol'];

  $auction_id = isset($_POST['auction_id']) ? intval($_POST['auction_id']) : false;
  if ($auction_id) {
  
   
    // get bids (use same code as display)
    $table_name = $wpdb->prefix . "wpa_bids";
    if ($engine != REVERSE_ENGINE) {
        $strSQL = "SELECT bidder_wordpress_id, bidder_name, bidder_email, bidder_url ,date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type";
    } else {
        $strSQL = "SELECT bidder_wordpress_id, bidder_name, bidder_email, bidder_url ,date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price, bid_type";
    }
    $rows = $wpdb->get_results ($strSQL);
    
    $topbidder = "";
    $firstbiddate = "";
    $lastbiddate = "";
	$p = "";
	$numbids = 0;

    foreach ($rows as $bid) {

		$numbids++;
		
		$p .= '<li class="media">';
		if ( $bid->bidder_wordpress_id != "") {
			$p .= '<a class="pull-left" href="'.get_author_posts_url($bid->bidder_wordpress_id).'" rel="nofollow">'.get_avatar( $bid->bidder_email, 45 ).'</a>';
			$p .= '<p><a href="'.get_author_posts_url($bid->bidder_wordpress_id).'" rel="nofollow" data-toggle="tooltip" data-placement="top" title="View profile">'.anon_bidder_name($bid->bidder_name, $anonymizebidder).'</a>';
		} else {
			$p .= '<a class="pull-left">'.get_avatar( $bid->bidder_email, 45 ).'</a>';
			$p .= '<p>'.anon_bidder_name($bid->bidder_name, $anonymizebidder).'</a>';	   
		}
		   
		$p .= ' '.__('bid','wpauctions').' <strong>'.$currencysymbol.number_format($bid->current_bid_price, 2, '.', ',').'</strong><span>'.wpa_date(get_date_from_gmt($bid->date));
		if ($bid->bid_type == "auto") $p .= ' ['.__('auto','wpauctions').']';
		if ($bid->bid_type == "advance") $p .= ' ['.__('increased max bid','wpauctions').']';
		$p .= '</span></p></li>';

		if ($topbidder == "") {
        	$topbidder = anon_bidder_name($bid->bidder_name, $anonymizebidder);
			$lastbiddate = human_time_diff( strtotime(get_date_from_gmt($bid->date)) , current_time('timestamp'));
		}
		$firstbiddate = human_time_diff( strtotime(get_date_from_gmt($bid->date)) , current_time('timestamp')); // keeps overwriting till we get last one    
	}
    $bids = "<ul>".$p."</ul>";  


  	// prepare result
  	$table_name = $wpdb->prefix . "wpa_auctions";
  	$strSQL = "SELECT current_price,start_price, reserve_price, BIN_price, date_end, customincrement FROM $table_name WHERE id=".$auction_id;
  	$row = $wpdb->get_row ($strSQL);

    if ($row != null) {


	  	// 22nd March 2017 - Added next bid code - this needs to be refactored at some point
	  	
	  	$customincrement = $row->customincrement;
	  	$current_price = $row->current_price;
	  	$start_price = $row->start_price;
	  	
	 	// engine specific code
		switch ($engine) {
		case 1: // standard
			if ($current_price >= $start_price) {
				$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
			} else {
				$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
			}
	
			$maximumbid_message = __('Enter Your Maximum Bid','wpauctions');
			$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " " . __('or higher','wpauctions'). " ";
			break;
	
		case 2: // simple
			if ($current_price >= $start_price) {
				$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
			} else {
				$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
			}
	
			$maximumbid_message = __('Enter Your Bid','wpauctions');
			$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " " .__('or higher','wpauctions');
			break;
	
		case 3: // reverse
			if ( $current_price == 0) {
				$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
			} else {
				$nextbid = $currencysymbol . number_format($current_price - wpa_get_increment($current_price,$customincrement), 2, '.', ',');
			}
			$maximumbid_message = __('Place Bid [Reverse Auction]','wpauctions');
			$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " ".__('or lower','wpauctions');
			break;
			
		case 4: // quickbuy
			if ($current_price >= $start_price) {
				$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
				$thisbid = number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
			} else {
				$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
				$thisbid = number_format($start_price, 2, '.', ',');
			}
	
			$maximumbid_message = __('Click to Bid','wpauctions');
			$bidhigher_message = __('Next Bid','wpauctions')." " . $nextbid;
			break;		
			
		}
	 



		if ($row->reserve_price > 0) {
		   if ($row->reserve_price > $row->current_price)
		      $reservestring =' [<em>'.__('Not met','wpauctions').'</em>]';
		   else
		      $reservestring =' [<strong>'.__('Met','wpauctions').'</strong>]';
		} else {
		   $reservestring =' [<em>'.__('n/a','wpauctions').'</em>]';  
		}	 

       $result = wpa_get_price($row->current_price,$row->start_price,$row->BIN_price,$currencysymbol," ");

       $result .= "|";

       if (!empty($topbidder)) {
          $result .= "<strong>".__('Winning','wpauctions').":</strong> ".$topbidder;
       } else {
          $result .= "&nbsp;";
       }

       $result .= "|";

       if (!empty($firstbiddate)) {
          $result .= '<strong>'.__('First Bid','wpauctions').':</strong> <abbr title="'.$firstbiddate.'">'.$firstbiddate.'</abbr> '.__('ago','wpauctions');
       } else {
          $result .= '<strong>'.__('First Bid','wpauctions').':</strong> N/A';
       }

       $result .= "|";

       if (!empty($lastbiddate)) {
          $result .= '<strong>'.__('Last Bid','wpauctions').':</strong> <abbr title="'.$lastbiddate.'">'.$lastbiddate.'</abbr> '.__('ago','wpauctions');
       } else {
          $result .= '<strong>'.__('Last Bid','wpauctions').':</strong> N/A';
       }

       $result .= "|";
       
       $result .= __('Reserve','wpauctions').': '.$reservestring;

       $result .= "|";
       
       $result .= $bids;

       $result .= "|";

       $result .= $numbids;
       
       $result .= "|";
       
       $result .= wpa_date(get_date_from_gmt($row->date_end));       

       $result .= "|";
       
       $result .= $bidhigher_message; 
       
    } else {
        $result = 0;
    }

    echo $result;
  } else {
     echo "AJAX ERROR: No auction specified";
  }
  
  // exit so we don't have to take additional load
  exit;

endif;


if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['update_price'])):

  global $wpdb;

  $options = get_option('wp_auctions');
  $anonymizebidder = $options['anonymizebidder'];
  $engine = $options['engine'];
  $countdown = $options['countdown'];
  $currencysymbol = $options['currencysymbol'];

  $auction_id = isset($_POST['auction_id']) ? intval($_POST['auction_id']) : false;
  if ($auction_id) {
  
    // get bids (use same code as display)
    $table_name = $wpdb->prefix . "wpa_bids";
    if ($engine != REVERSE_ENGINE) {
        $strSQL = "SELECT bidder_name, bidder_url ,date, current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type";
    } else {
        $strSQL = "SELECT bidder_name, bidder_url ,date, current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price, bid_type";
    }
    $rows = $wpdb->get_results ($strSQL);
    
    $topbidder = "";
    foreach ($rows as $bid) {
		if ($topbidder == "") {
        	$topbidder = anon_bidder_name($bid->bidder_name, $anonymizebidder);
			break;  // perf help
      }
    }


  	// prepare result
  	$table_name = $wpdb->prefix . "wpa_auctions";
  	$strSQL = "SELECT current_price,start_price, BIN_price, date_start, date_end, customincrement FROM $table_name WHERE id=".$auction_id;
  	$row = $wpdb->get_row ($strSQL);
  	
  	
	// new code
		// countdown stuff
		$end_dateGMT = $row->date_end;
		$start_dateGMT = $row->date_start;

		// calculate difference between now and end date .. we'll do this with server timezone
		$today = strtotime("now");
		$auctionend = strtotime($end_dateGMT);
		$secsdiff = $auctionend - $today;

		switch ($countdown) {
		case 0:
			$showcountdown = false;
			break;
		case 999:
			$showcountdown = true;
			break;
		default:
			$showcountdown = ( $secsdiff < $countdown );
		}
  	
  	
  	// 22nd March 2017 - Added next bid code - this needs to be refactored at some point
  	
  	$customincrement = $row->customincrement;
  	$current_price = $row->current_price;
  	$start_price = $row->start_price;
  	
 	// engine specific code
	switch ($engine) {
	case 1: // standard
		if ($current_price >= $start_price) {
			$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
		}

		$maximumbid_message = __('Enter Your Maximum Bid','wpauctions');
		$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " " . __('or higher','wpauctions'). " ";
		break;

	case 2: // simple
		if ($current_price >= $start_price) {
			$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
		}

		$maximumbid_message = __('Enter Your Bid','wpauctions');
		$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " " .__('or higher','wpauctions');
		break;

	case 3: // reverse
		if ( $current_price == 0) {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($current_price - wpa_get_increment($current_price,$customincrement), 2, '.', ',');
		}
		$maximumbid_message = __('Place Bid [Reverse Auction]','wpauctions');
		$bidhigher_message = __('Bid','wpauctions')." " . $nextbid . " ".__('or lower','wpauctions');
		break;
		
	case 4: // quickbuy
		if ($current_price >= $start_price) {
			$nextbid = $currencysymbol . number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
			$thisbid = number_format($current_price + wpa_get_increment($current_price, $customincrement), 2, '.', ',');
		} else {
			$nextbid = $currencysymbol . number_format($start_price, 2, '.', ',');
			$thisbid = number_format($start_price, 2, '.', ',');
		}

		$maximumbid_message = __('Click to Bid','wpauctions');
		$bidhigher_message = __('Next Bid','wpauctions')." " . $nextbid;
		break;		
		
	}
 	
  	
  	

    if ($row != null) {
       $result = wpa_get_price($row->current_price,$row->start_price,$row->BIN_price,$currencysymbol," <br /> ");
       $result .= "|";
       if (!empty($topbidder)) {
          $result .= "<strong>".__('Winning','wpauctions').":</strong> ".$topbidder;
       } else {
          $result .= "&nbsp;";
       }
       $result .= "|";
       $result .= $showcountdown;
       $result .= "|";
       $result .= $secsdiff;
       $result .= "|";
       $result .= wpa_date(get_date_from_gmt($row->date_end));
       $result .= "|";
       $result .= $bidhigher_message; 
       
    } else {
        $result = 0;
    }

    echo $result;
  } else {
     echo "AJAX ERROR: No auction specified";
  }
  
  // exit so we don't have to take additional load
  exit;

endif;


if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['update_bids'])):

  global $wpdb;

  $options = get_option('wp_auctions');
  // 2013.05.09 mensmaximus
  $anonymizebidder = $options['anonymizebidder'];
  $currencysymbol = $options['currencysymbol'];

  $auction_id = isset($_POST['auction_id']) ? $_POST['auction_id'] : false;
  if ($auction_id) {

    // get bids
    $table_name = $wpdb->prefix . "wpa_bids";
    $strSQL = "SELECT bidder_name, bidder_url ,date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type";
    $rows = $wpdb->get_results ($strSQL);
 
    $p = "";
    foreach ($rows as $bid) {
      $p .= '<li>';
       if ($bid->bidder_url != "" && $customcontact == "URL") {
          $p .= '<a href="'.$bid->bidder_url.'" rel="nofollow">'.anon_bidder_name($bid->bidder_name, $anonymizebidder).'</a>';
       } else {
          $p .= anon_bidder_name($bid->bidder_name, $anonymizebidder);
       }
       $p .= ' '.__('bid','wpauctions').' '.$currencysymbol.number_format($bid->current_bid_price, 2, '.', ',').' '.__('on','wpauctions').' '.wpa_date(get_date_from_gmt($bid->date));
       if ($bid->bid_type == "auto") $p .= ' ['.__('auto','wpauctions').']';
       if ($bid->bid_type == "advance") $p .= ' ['.__('increased max bid','wpauctions').']';
       $p .= '</li>';
     }	

     $result = "<ol>".$p."</ol>";

    echo $result;
  } else {
     echo "AJAX ERROR: No auction specified";
  }  
  
  // exit so we don't have to take additional load
  exit;

endif;


if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['debug'])):
    $options = get_option('wp_auctions');
  if ($options['remotedebug'] != "" ) { 
        echo '<style type="text/css">';
        echo '.wpa_debug_container {text-align: center;}';
        echo '.wpa_debug_container a {background: transparent !important; color: #000 !important;}';
        echo '.wpa_debug_table {margin: 0px auto 25px auto; width: 600px; }';
        echo '.wpa_debug_hrow {font-size: 125%; line-height: 125%;}';
        echo '.wpa_debug_orow { background-color: #bbb; }';
        echo '.wpa_debug_erow { background-color: #ddd; }';
        echo '.wpa_debug_orow:hover, .wpa_debug_erow:hover { background-color: #9999CC; } ';
        echo '.wpa_debug_hcol {padding: 3px; }';
        echo '.wpa_debug_dcol {width: 200px; padding: 3px; }';
        echo '.wpa_debug_ccol {font-weight: bold; padding: 3px; }';
        echo '.wpa_debug_icol {padding: 3px; }';
        echo '.wpa_debug_pa {font-weight: bold; font-style: normal;}';
        echo '.wpa_debug_pi {font-weight: normal; font-style: oblique;}';    
        echo '.wpa_debug_plugin {text-align: left; font-size: 11px; width: 600px; display: block; margin: 0 auto;}';
        echo '</style>';
    
        echo '<div class="wpa_debug_container">';
        echo '<h1>WP Auctions Remote Debug Screen</h1>';
        echo '<table class="wpa_debug_table">';
        echo '<tr class="wpa_debug_hrow">';
        echo '<td class="wpa_debug_hcol" colspan="2">WPA Settings</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">Version Number</td>';
        echo '<td class="wpa_debug_ccol">'.$wpa_version.'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">Plugin URL</td>';
        echo '<td class="wpa_debug_ccol">'. WPA_PLUGIN_URL . '</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_hrow">';
        echo '<td class="wpa_debug_hcol" colspan="2">Date- and Time Settings</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">Current Time GMT</td>';
        echo '<td class="wpa_debug_ccol">'. gmdate('r', time()) .'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">Current Time Server</td>';
        echo '<td class="wpa_debug_ccol">'. date('r', time()) .'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">Current Time Wordpress</td>';
        echo '<td class="wpa_debug_ccol">'. date('r', current_time('timestamp')) .'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">PHP Timezone Runtime</td>';
        echo '<td class="wpa_debug_ccol">';
        if (date_default_timezone_get()) {
            echo date_default_timezone_get();
        }
        echo '</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">PHP Timezone Init</td>';
        echo '<td class="wpa_debug_ccol">';
        if (ini_get('date.timezone')) {
            echo ini_get('date.timezone');
        }
        echo '</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">Wordpress Timezone</td>';
        echo '<td class="wpa_debug_ccol">'.get_option('timezone_string').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">Wordpress GMT Offset</td>';
        echo '<td class="wpa_debug_ccol">'.get_option('gmt_offset').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_hrow">';
        echo '<td class="wpa_debug_hcol" colspan="2">Wordpress Settings</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">Version Number</td>';
        echo '<td class="wpa_debug_ccol">'.get_bloginfo('version').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">Language</td>';
        echo '<td class="wpa_debug_ccol">'.get_bloginfo('language').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">URL</td>';
        echo '<td class="wpa_debug_ccol">'.get_bloginfo('wpurl').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">Charset</td>';
        echo '<td class="wpa_debug_ccol">'.get_bloginfo('charset').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_orow">';
        echo '<td class="wpa_debug_dcol">Administrator</td>';
        echo '<td class="wpa_debug_ccol">'.get_bloginfo('admin_email').'</td>';
        echo '</tr>';
        echo '<tr class="wpa_debug_erow">';
        echo '<td class="wpa_debug_dcol">Template</td>';
        echo '<td class="wpa_debug_ccol">'.get_bloginfo('template_url').'</td>';
        echo '</tr>';
    
        if(!function_exists('get_plugins')) {
            require_once (ABSPATH . 'wp-admin/includes/plugin.php');
        }
        
        $my_plugin_array = get_plugins();
        $my_plugin_count = count($my_plugin_array);
        echo '<tr class="wpa_debug_hrow">';
        echo '<td class="wpa_debug_hcol" colspan="2">Installed Plugins ('. $my_plugin_count .')</td>';
        echo '</tr>';
        $my_row_count = true;
        foreach ($my_plugin_array as $plugin_container => $plugin_data) {
                if ($my_row_count = !$my_row_count){
                echo '<tr class="wpa_debug_orow">';
            } else {
                echo '<tr class="wpa_debug_erow">';
            }
            if(is_plugin_active($plugin_container)) {
                $my_debug_pclass = 'wpa_debug_pa';
            } else {
                $my_debug_pclass = 'wpa_debug_pi';
            }
            echo '<td class="wpa_debug_dcol '. $my_debug_pclass .'">'. $plugin_data['Name'] .'</td>';
            echo '<td class="wpa_debug_icol '. $my_debug_pclass .'">';
                echo $plugin_data['Version'] . ' (';
                echo $plugin_data['AuthorURI'] . ')<br />';
                echo '<a href="'. $plugin_data['PluginURI'] .'" target="_blank">'. $plugin_data['AuthorName'] .'</a>';
            echo '</td>';
            echo '</tr>';
        }
        echo '</tr>';
        echo '</table>';
        echo '</div>';
    
    //        Room for additional debugin output
    //        $my_extra_debug = 'something';
    //        echo '<div class="wpa_debug_plugin">';
    //        echo '<pre>';
    //        print_r ($my_extra_debug);
    //        echo '</pre>';
    //        echo '</div>';

  phpinfo();
} else {
  echo "Remote Debug disabled - you can turn this on in your Administration console";
}
endif;

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['postwatch'])):

  // check security
  check_ajax_referer( "WPA-nonce" );

	// process posted values here
	$auction_id = $_POST['auction_id'];
	$watch_email = strip_tags(stripslashes($_POST['watch_email']));

  // and to make doubly sure
  //$watch_email = mysql_real_escape_string($watch_email);
  //$auction_id = mysql_real_escape_string($auction_id);
 
  if (filter_var($watch_email, FILTER_VALIDATE_EMAIL)) {
  	$table_name = $wpdb->prefix . "wpa_watchlist";
  	$sql = "INSERT INTO ".$table_name." (id, auction_id, watch_email) VALUES (NULL, ".$auction_id.", '".$watch_email."' );";
  	$result = $wpdb->query($sql);

  	if ($result)
      _e("You will be notified of any changes to this auction.",'wpauctions');
      
  } else {
  	// error conditions
	if ($watch_email == "enter your email") {
      _e("You must log in to watch this auction.",'wpauctions');
	} else {
      _e("Please specify a valid email address. Email specified: ",'wpauctions');
      echo $watch_email;
	}  	
  	
  }
  
  exit;
endif;

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['postauction'])):

  // check security
  check_ajax_referer( "WPA-nonce" );

	// process posted values here
	$auction_id = $_POST['auction_id'];
	$bidder_name = htmlspecialchars(strip_tags(stripslashes($_POST['bidder_name'])), ENT_QUOTES);
	$bidder_email = strip_tags(stripslashes($_POST['bidder_email']));
	$bidder_url = htmlspecialchars(strip_tags(stripslashes($_POST['bidder_url'])), ENT_QUOTES);
	$max_bid = $_POST['max_bid'];
	$BIN_amount = $_POST['BIN_amount'];

   $result = wpa_process_bid( $auction_id, $bidder_name, $bidder_email, $bidder_url, $max_bid, $BIN_amount );
   
    echo $result;
	exit;

	endif;

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['queryauction'])):

 // 0 = id
 // 1 = name
 // 2 = description
 // 3 = current_price
 // 4 = date_create
 // 5 = date_end
 // 6 = start_price 
 // 7 = image_url
 // 8 = "auction ended?"
 // 9 = winner
 // 10= winning_price
 // 11= BIN_price
 // 12= extraimage1 
 // 13= extraimage2
 // 14= extraimage3
 // 15= "next_bid"
 // 16= shipping_price
 // 17= shipping_to
 // 18= "otherimages"
 // 19= reserve_price
 // 20= engine
 // 21= shipping_from
 // 22= "auction started?"
 // 23= variable_shipping
 // 24= terms
 // 25= postdesc
 // 26= customincrement
 // 27= RTB status

	global $wpdb;
  $options = get_option('wp_auctions');
  $requesttobid = $options['requesttobid'];
  
  // thumbnail size is set here
  $thumbnail_size = 50;
  $image_size = 300;
  $image_height = 250;
 
	function fail($s) { header('HTTP/1.0 406 Not Acceptable'); die($s);}

  // check security
  check_ajax_referer( "WPA-nonce" );

	// process query string here
	$auction_id = $_POST['auction_ID'];

	// validate input
	if (!is_numeric($auction_id)) // ID not numeric
		fail(__('Invalid Auction ID specified','wpauctions'));
		
    // confirm if auction has ended or not
    check_auction_end($auction_id);

  	// prepare result
  	$table_name = $wpdb->prefix . "wpa_auctions";
  	$strSQL = "SELECT id, name,description,current_price,date_create,date_end,start_price,image_url, '".current_time('mysql',"1")."' < date_end, winner, winning_price, BIN_price, extraimage1, extraimage2, extraimage3, 0.00 as 'next_bid', shipping_price, shipping_to, 'placeholder' as 'otherimages', reserve_price, engine, shipping_from, '".current_time('mysql',"1")."' > date_start, variable_shipping, terms, postdesc,customincrement, 0 as RTB_status FROM $table_name WHERE id=".$auction_id;
  	$rows = $wpdb->get_row ($strSQL, ARRAY_N);

  	// send back result
    if (!($rows)) // no records found
       fail(__('Cannot locate auction','wpauctions'));

	$fee = wpa_expressfee();
	
	if ($fee != "") {
		$rows[2] .= "<p class='wpa-description-template'>". __('The following fee will be added to this auction: ','wpauctions') . $fee . "</p>";	
	}
	   
	   	   	   
    // handle template fields
    if ($rows[25] != "") {
      $template = unserialize($rows[25]);
      $strTemplateData = $template["data"];
      
      if (is_array($strTemplateData)) {
        foreach ($strTemplateData as $key => $value)
        {
           // strip out _s
           $newkey = str_replace("_", " ", $key);
           $rows[2] .= "<p class='wpa-description-template'><strong>$newkey :</strong> $value</p>";
        }
      }
    }
	
    // pass image through resizer    
    $temp = $rows[7];
    $rows[7] = wpa_resize ($rows[7],$image_size,$image_height);
    
    $rows[18] = "";
    // other images could be blank .. in which case, don't resize
    if ($rows[12] != "") {
       $rows[18] = $rows[18].'^'.wpa_resize ($rows[12],$thumbnail_size);
       $rows[12] = wpa_resize ($rows[12],$image_size,$image_height);
    }
    if ($rows[13] != "") {
       $rows[18] = $rows[18].'^'.wpa_resize ($rows[13],$thumbnail_size);
       $rows[13] = wpa_resize ($rows[13],$image_size,$image_height);
    }       
    if ($rows[14] != "") { 
       $rows[18] = $rows[18].'^'.wpa_resize ($rows[14],$thumbnail_size);
       $rows[14] = wpa_resize ($rows[14],$image_size,$image_height);
    }
           
    // v4 - always append    
    $rows[18] = $rows[18] . '^'.wpa_resize ($temp,$thumbnail_size);    
        
    // normalise dates
    $rows[4] = date('dS M Y h:i A',strtotime(get_date_from_gmt($rows[4])));
    $rows[5] = date('dS M Y h:i A',strtotime(get_date_from_gmt($rows[5])));

    // insert next increment if not starting price
    if ($rows[20] == 3) { // handle reverse 
      if ( $rows[3] > 0 ) {
         $rows[15] = number_format($rows[3] - wpa_get_increment($rows[3], $rows[26]), 2, '.', ',');
      } else {
         $rows[15] = $rows[6];
      }
    } else {
      if ($rows[3] >= $rows[6]) {
         $rows[15] = number_format($rows[3] + wpa_get_increment($rows[3], $rows[26]), 2, '.', ',');
      } else {
         $rows[15] = $rows[6];
      }    
    }
  
    // process RTB - we only need to do this if RTB is on
    if ($requesttobid == "Yes") {
    	    // check if we have a request
	     if (is_user_logged_in()) {
	        global $current_user;
	        get_currentuserinfo();
	     
	        $bidder_id = $current_user->ID;
	      } else {
	         $bidder_id = 0;
	      }
	      
	      $table_name = $wpdb->prefix . "wpa_bidderrequests";
        $strSQL = "SELECT * FROM $table_name WHERE auction_id=".$auction_id." AND bidder_id=".$bidder_id;
        $row = $wpdb->get_row ($strSQL);

        if ($row != null) {
           $rows[27] = $row->RTB_Status;
        }
    } 
  
	// prepare results   	
  $result_set = implode("|", $rows);  
        	
    echo $result_set;
	exit;
endif;

if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['querybids'])):

	global $wpdb;

	$options = get_option('wp_auctions');
	$anonymizebidder = $options['anonymizebidder'];

	function fail($s) { header('HTTP/1.0 406 Not Acceptable'); die($s);}

	// check security
	check_ajax_referer( "WPA-nonce" );

	// process query string here
	$auction_id = $_POST['auction_ID'];
	$engine = $_POST['engine'];

	// validate input
	if (!is_numeric($auction_id)) // ID not numeric
		fail(__('Invalid Auction ID specified','wpauctions'));
		
	// prepare result
	$table_name = $wpdb->prefix . "wpa_bids";
	
	if ($engine != REVERSE_ENGINE) {
	   $strSQL = "SELECT bidder_name, bidder_url ,date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price DESC, bid_type";
	} else {
	   $strSQL = "SELECT bidder_name, bidder_url ,date,current_bid_price, bid_type FROM $table_name WHERE auction_id=".$auction_id." ORDER BY current_bid_price, bid_type";	
	}
	$rows = $wpdb->get_results ($strSQL, ARRAY_N);

	// send back result
    if (!($rows)) // no records found
       $result_set="";
    else {
	//	foreach ($rows as &$row) {
	// 		$row[2] = date('dS M Y h:i A',strtotime(get_date_from_gmt($row[2]))); // convert dates to WP timezone
	//	}

	// change above code as it didn't work in PHP 4

		foreach($rows as $i=>$row){
			
			$row[2] = wpa_date(get_date_from_gmt($row[2])); // convert dates to WP timezone

			$row[0] = anon_bidder_name($row[0], $anonymizebidder);
			
			$rows[$i]=$row;
		}
		
		$result_set = wpa_implode_r("|",$rows);
    }
      	
    echo $result_set;
	
	exit;
endif;


if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['queryother'])):

	global $wpdb;

	function fail($s) { header('HTTP/1.0 406 Not Acceptable'); die($s);}

  // check security
  check_ajax_referer( "WPA-nonce" );

	// process query string here
	$auction_id = $_POST['auction_ID'];

	// validate input
	if (!is_numeric($auction_id)) // ID not numeric
		fail(__('Invalid Auction ID specified','wpauctions'));
		
	// prepare result
	$table_name = $wpdb->prefix . "wpa_auctions";
	$strSQL = "SELECT id,name,image_url,current_price,start_price,0.00 as 'next_bid', BIN_price FROM $table_name WHERE id <> ".$auction_id." AND '".current_time('mysql',"1")."' < date_end AND '".current_time('mysql',"1")."' > date_start ORDER BY RAND() LIMIT 4";
	$rows = $wpdb->get_results ($strSQL, ARRAY_N);

      foreach($rows as $i=>$row){

        $row[2] = wpa_resize($row[2],50);

            // insert current price
           if ($row[3] >= $row[4]) {
              $row[5] = $row[3];
           } else {
              $row[5] = $row[4];
           }            

         // replace the row in the table
         $rows[$i]=$row;
      }

	// send back result
    if (!($rows)) // no records found
       $result_set="";
    else
       $result_set = wpa_implode_r("|",$rows);
      	
    echo $result_set;
	exit;
endif;
?>