<?PHP

if (!$_POST){ header('Location: '.$site_url.'/?error=no_post'); }

/** Need to ltrim and rtrim commas before insertion **/

//Insert into database
$errmsg = NULL;
//Check for blank fields
   if ((!$_POST[name])) $errmsg = $errmsg.'Race name, ';  
   if ($_POST[month]==0) $errmsg = $errmsg.'Race month, ';
   if ($_POST[day]==0) $errmsg = $errmsg.'Race day, ';
   if ($_POST[type]==0) $errmsg = $errmsg.'Race type, ';
   if (!$_POST[indivfee]) $errmsg = $errmsg.'Individual entry fee, ';
   if (!$_POST[swim]) $errmsg = $errmsg.'1st event distance, ';
   if (!$_POST[bike]) $errmsg = $errmsg.'2nd event distance, ';
   //if (!$_POST[run]) $errmsg = $errmsg.'3rd event distance, '; 
   if (!$_POST[state]) $errmsg = $errmsg.'State, ';
   if (!$_POST[city]) $errmsg = $errmsg.'City, ';
   if (!$_POST[address]) $errmsg = $errmsg.'Address, ';
   if (!$_POST[phone]) $errmsg = $errmsg.'Phone, ';
   if (!$_POST[email]) $errmsg = $errmsg.'Email, ';
   if (strlen($_POST[courseinfo]) < 4) $errmsg = $errmsg.'Course info, ';
   if (strlen($_POST[moreinfo]) < 4) $errmsg = $errmsg.'More info, ';
   if (strlen($_POST[directions]) < 4) $errmsg = $errmsg.'Directions, ';
   if (!$_POST[website]) $errmsg = $errmsg.'Website, ';
   if (isset($errmsg)) {
       $errmsg = 'The following fields cannot be left blank: '.$errmsg;
       $errmsg = rtrim($errmsg, ', ');
   }
   if (!is_numeric($_POST[swim])) $errmsg = $errmsg.'1st event distance must be a number ONLY, ';
   if (!is_numeric($_POST[bike])) $errmsg = $errmsg.'2nd event distance must be a number ONLY, ';
   if ($_POST[run] != "" && !is_numeric($_POST[run])) $errmsg = $errmsg.'3rd event distance must be a number ONLY, ';
   if( preg_match('/[^a-zA-Z0-9\. ]/', $_POST[name]) ) {
	  // Contains invalid characters.
	  $errmsg = "Please use only letters and numbers in the name";
   }
   
   //Check for duplicate entry
   if(isset($_POST['add_race'])) {
		$sql_Races = "SELECT uid, name, type FROM gforum_Triathlons WHERE valid = 1";
					  
		$results_Races = mysql_query($sql_Races) or die(mysql_error());
		
		$arr_Races = array("");
		$arr_Duplicates = array("");
		$i = 0;
		while($row_races = mysql_fetch_array($results_Races)) {
			// build an array that we can loop through. We will need to then duplicate this
			$arr_Races[$i] = $row_races;
			$i++;
		}
		
		$spacer = "";
		if ($errmsg) { $spacer = "<br />"; }
		$dupmsg = NULL;
		
		foreach ($arr_Races AS $race) {	
			if ($dupmsg) { $spacer = "<br />"; }
			similar_text($race['name'], $_POST['name'], $percent);
			if ($race[uid] != $_POST[uid] && $percent >= 75 && $race['type'] == $_POST['type']) {
				// DEBUG: which USERUID are we processing
				$dupmsg = $dupmsg.$spacer."POTENTIAL DUPLICATE: <a href=\"https://slowtwitch.com/calendar/individual.php?uid=".$race[uid]."\" target=\"_blank\">".$race[uid].". ".$race[name]." (".round($percent,0)."%)</a> Please check this race first and update it instead of adding a new one.";
			}
		}
   }
   //end check for duplicate entry
   // BEGIN ERROR MESSAGE CHECK
   if(!$errmsg){
      $race_uid_fk = mysql_real_escape_string(trim($_POST[uid]));
      $editor_user_id_fk = mysql_real_escape_string(trim($_POST[edited_by]));
   	  $name = mysql_real_escape_string(trim($_POST[name]));
	  $nametag = strtolower(str_replace(" ","", $name));
	  if(strlen($nametag) > 12){ //Shorten it
		$nametag = substr($nametag, 0, 12);
	  }
	  $state = $_POST[state];
	  $statetag = strtolower(str_replace(" ","", $state));
	  $type = $_POST[type];
	  $bike_surface = $_POST[bike_surface];
	  if ($_POST[draft_legal] != "") { $draft_legal = $_POST[draft_legal]; } else { $draft_legal = 0; }
	  if ($_POST[kids_race] != "") { $kids_race = $_POST[kids_race]; } else { $kids_race = 0; }
	  $indivfee = mysql_real_escape_string(trim($_POST[indivfee]));
	  $teamfee = mysql_real_escape_string(trim($_POST[teamfee]));
	  if ($_POST[registration] != "") { $registration = $_POST[registration]; } else { $registration = 0; }
	  $swim = $_POST[swim];
	  $oneunit = $_POST[oneunit];
	  $twounit = $_POST[twounit];
	  $threeunit = $_POST[threeunit];
	  $onetype = $_POST[onetype];
	  $twotype = $_POST[twotype];
	  $threetype = $_POST[threetype];
	  $bike = $_POST[bike];
	  if ($_POST[run] != "") { $run = $_POST[run]; } else { $run = 0; }
	  $city = mysql_real_escape_string(trim($_POST[city]));
	  $address = mysql_real_escape_string(trim($_POST[address]));
	  $phone = mysql_real_escape_string(trim($_POST[phone]));
	  $email = mysql_real_escape_string(trim($_POST[email]));
	  $courseinfo = substr(mysql_real_escape_string(trim($_POST[courseinfo])), 0, 4096);
	  $moreinfo = substr(mysql_real_escape_string(trim($_POST[moreinfo])), 0, 4096);
	  $directions = substr(mysql_real_escape_string(trim($_POST[directions])), 0, 4096);
	  $substring = "http";
	  $register = mysql_real_escape_string(trim($_POST[register]));
	  $website = mysql_real_escape_string(trim($_POST[website]));
      $results = mysql_real_escape_string(trim($_POST[results]));
	  if (!is_int(strpos($register, $substring))) {
			$register = "http://".$register;
	  }
	  if (!is_int(strpos($website, $substring))) {
			$website = "http://".$website;
	  }
	  $hour = $_POST[hour];
	  //if($_POST[daypart] == 1){ $hour = $hour + 12; } 
	  $minute = $_POST[minute];
	  $year = $_POST[year];
	  $month = $_POST[month];
	  $day = $_POST[day];
	  $date = "$year-$month-$day $hour:$minute:00";
	  $uid = $_POST[uid];
	  $submitted_by = $_POST[submitted_by];
	  $edited_by = $_POST[edited_by];
	  $edit_timestamp = time();

      if($type == 1){ $typename = 'Triathlon'; }
      if($type == 2){ $typename = 'Duathlon'; }
      if($type == 3){ $typename = 'Other'; }
      
   	// BEGIN CONFIRM ENTRY CHECK
     if($_POST[confirm_entry] == 1){
  
    // BEGIN POINTS CALCULATIONS
  
   	  $one_points = 0;
	  $two_points = 0;
	  $three_points = 0;
	
 	  $arrSwimPoints = array(1 => 17.6, 2 => 0.011, 3 => 0.01, 4 => 11);
	  $arrBikePoints = array(1 => 1, 2 => 0.00062, 3 => 0.00057, 4=> .62);
	  $arrRunPoints = array(1 => 4, 2 => 0.0025, 3 => 0.0023, 4 => 2.5);
	  $arrPaddlePoints = array(1 => 2.6667, 2 => 0.00167, 3 => 0.00153, 4 => 1.6667);
	  $arrSkiPoints = array(1 => 2.75, 2 => 0.00172, 3 => 0.00158, 4 => 1.72);
	  $arrMtbPoints = array(1 => 2, 2 => 0.00124, 3 => 0.00114, 4=> 1.24);
	  $arrPoints = array(1 => $arrSwimPoints, 2=> $arrBikePoints, 3 => $arrRunPoints, 4 => $arrPaddlePoints, 5 => $arrSkiPoints); 
	  
	  $one_points = $swim*$arrPoints[$onetype][$oneunit];
	  $two_points = $bike*$arrPoints[$twotype][$twounit];
	  $three_points = $run*$arrPoints[$threetype][$threeunit];
	  
      $points = $one_points + $two_points + three_points;
	
	  if ($points < 40) { $pointclass = 1; 
	  } elseif ($points >= 40 AND $points < 100) { $pointclass = 2; 
	  } elseif ($points >= 100 AND $points < 180) { $pointclass = 3; 
	  } else { $pointclass = 4; } 
	
	// END POINTS CALCULATION
  
  if(isset($_POST['add_race'])){
		$sql = "INSERT INTO gforum_Triathlons(onetype, twotype, threetype, oneunit, twounit, threeunit, racetags, valid, name, nametag, date, type, indivfee, teamfee, swim, bike, bike_surface, draft_legal, kids_race, run, state, statetag, city, address, phone, email, courseinfo, moreinfo, directions, register, website, submitted_by, one_points, two_points, three_points, points, pointclass, registration) VALUES('$onetype', '$twotype', '$threetype', '$oneunit', '$twounit', '$threeunit', '0', 0, '$name', '$nametag', '$date', $type, '$indivfee', '$teamfee', $swim, $bike, $bike_surface, $draft_legal, $kids_race, $run, '$state', '$statetag', '$city', '$address', '$phone', '$email', '$courseinfo', '$moreinfo', '$directions', '$register', '$website', '$submitted_by', $one_points, $two_points, $three_points, $points, $pointclass, $registration)"; 
		mysql_query($sql) OR die(mysql_error()); 
	 	header('Location: '.$site_url.'/add.php?confirmed=yes');
   } elseif(isset($_POST['save_changes'])) {
		$sql = "INSERT INTO gforum_TriathlonsEdits(race_uid_fk, editor_user_id_fk, edit_timestamp, onetype, twotype, threetype, oneunit, twounit, threeunit, name, nametag, date, type, indivfee, teamfee, swim, bike,  bike_surface, draft_legal, kids_race, run, state, statetag, city, address, phone, email, courseinfo, moreinfo, directions, register, website, submitted_by, one_points, two_points, three_points, points, pointclass, registration) VALUES('$race_uid_fk', '$editor_user_id_fk', '$edit_timestamp', '$onetype', '$twotype', '$threetype', '$oneunit', '$twounit', '$threeunit', '$name', '$nametag', '$date', $type, '$indivfee', '$teamfee', $swim, $bike, $bike_surface, $draft_legal, $kids_race, $run, '$state', '$statetag', '$city', '$address', '$phone', '$email', '$courseinfo', '$moreinfo', '$directions', '$register', '$website', '$submitted_by', $one_points, $two_points, $three_points, $points, $pointclass, $registration)"; 
		//echo $sql;
		mysql_query($sql) OR die(mysql_error());
		header('Location: '.$site_url.'/individual.php?uid='.$uid.'&wiki_change=success');
    } else {
		header('Location: '.$site_url.'/individual.php?uid='.$uid.'&changes=failure');
    }
  } else {
	$confirm = 1;
  } // END CONFIRM CHECK
} // END ERROR MESSAGE CHECK

?>
