<?php 
require('includes/settings.php');
require('includes/mysql_connect.php');
require('includes/funcs.php');

session_start();

if (!$_SESSION['randomString'] || $_SESSION['randomString'] == "")
{
	header('Location:contest_page1.php');
}
else
{
	// $randomString = $_SESSION['randomString'];
	$eligibleYN = $_SESSION['eligible'];
}

$p_email = '';
$p_bonus_code = '';
if (isset($_POST['submit']))
{

	//var_dump_err($_POST);

	$boolValidate = true;
	$strValidation = $strValidationB = '';
	
	$p_email = strtolower(sanitize($_POST["email"]));
	if (isset($_POST['bonus-code']))
		$p_bonus_code = sanitize($_POST['bonus-code']);
	else
		$p_bonus_code = '';
	$p_bonus_code_list = sanitize($_POST['codeListHidden']);

	if (strlen($p_bonus_code) > 10)
		$p_bonus_code = "FREE ENTRY";
	
	if (!$p_bonus_code_list || strlen($p_bonus_code_list) == 0)
		$p_bonus_code_list = $p_bonus_code;
	else
		$p_bonus_code_list .= ', ' . $p_bonus_code;
	
	// NB: "FREE ENTRY" is changed to "FREEENTRY" in the call below, so that parsing is consistent
	$p_bonus_code_list = str_replace(" ", "", $p_bonus_code_list); // remove spaces because they display nicely, but submit poorly
	$p_bonus_code_list = rtrim($p_bonus_code_list, ",");

//error_log("p_bonus_code_list = " . $p_bonus_code_list);

	if ($p_email == "" || !preg_match('/^[-\w\.]{1,40}\@[-\w\.]{1,40}\.\w{2,10}$/', $p_email))
	{
		$boolValidate = false;
		$strValidationB .= "<h3>Please enter your email address</h3>";
		//error_log($strValidationB);
	}
	
	//if ($p_bonus_code_list == null || !preg_match('/^([A-Z]{3}\d{3},?)+$/', $p_bonus_code_list))
//error_log($p_bonus_code_list);
	if ($p_bonus_code_list == null || !preg_match('/^(((FREEENTRY)|([A-Z]{3}\d{3})),?)+$/', $p_bonus_code_list))
	{
		$boolValidate = false;
		$strValidationB .= "<h3>Please enter a valid entry code</h3>";
		//error_log($strValidationB);
	}

	if ($boolValidate)
	{
	
		foreach (explode(',',$p_bonus_code_list) as $p_bonus_code)
		{
			$boolValidate = true;
			mysqli_begin_transaction($dbc);

			if ($p_bonus_code == $g_TestCode)
			{
				$intBonusCode = 1; // we have to assign it to something, so use the first real (test) code in the list 
			}
			elseif ($p_bonus_code == "FREEENTRY")
			{
				$intBonusCode = 0; // we have to assign it to something, so 0
			}
			else
			{
				//error_log("exploded code: " . $p_bonus_code);
				// if they've entered a bonus code lets make sure it hasn't been used before and is valid
				if ($p_bonus_code != '')
				{
					$check_code_sql = "SELECT intBonusCodeID from ".$g_KioskBonusCodesTableName." where strBonusCode = '$p_bonus_code' and ynUsed = 'N'";
					$check_code_result = getFromDatabase($check_code_sql);

					if(mysqli_num_rows($check_code_result) == 1)
					{
						$intBonusCodeFetch = mysqli_fetch_array($check_code_result);
						$intBonusCode = $intBonusCodeFetch[0];
					}
					else
					{
						$boolValidate = false;
						//$strValidationB .= '<p>That entry code has already been used or doesn\'t exist. </p>';
					}
				}
			}

			if ($boolValidate && $p_bonus_code != "")
			{
				$sql = "INSERT INTO ".$g_KioskTableName." (strEmail, intBonusCode, dateEntered) VALUES ('$p_email', '$intBonusCode', NOW())";
				$result = getFromDatabase($sql);
				$insertID = mysqli_insert_id($dbc);

				if ($insertID)
				{
					if (isset($_SESSION['insertID']) == false || $_SESSION['insertID'] == null || $_SESSION['insertID'] == '')
						$_SESSION['insertID'] = $insertID;
					else
						$_SESSION['insertID'] .= ',' . $insertID;

					$_SESSION['email'] = $p_email;

					if ($intBonusCode != 0) // when it is not a free code
					{
						$bonus_sql = "UPDATE ".$g_KioskBonusCodesTableName." set ynUsed = 'Y', intUsedBy=" .$insertID. "  where intBonusCodeID = '$intBonusCode'";
						$bonus_result = getFromDatabase($bonus_sql);
						mysqli_commit($dbc);
					}
				}
				else
				{
					mysqli_rollback($dbc);
					//$strValidationB = '<p>Sorry but your contest entry did not save to the database. Please try again.</p>';
				}
			}
		}
		header('Location:contest_page3.php');
	}
}
 ?>

<?php include('includes/header.php'); ?>
<body class="internal">
<script type="text/javascript">
	var isCheckingValidity = false;
	var isCodeValid = false;
	var isCheckingFreebee = false;
	var freeCount = 0;
	$(document).ready(function()
	{
		setTimeout(function(){$("#email").focus();}, 200);

		$("#bonus-code").on('input', function(evt)
		{
			var field = $(this);
			$("#bonus-code").css('background-color', '#ffffff');
			var fval = field.val().toUpperCase();
			field.val(fval);	// we always gotta go to upper case anyways, may as well do it right away
			var ndx = fval.length - 1;

			if (isCheckingValidity)
			{
				field.val(fval.substr(0,ndx));
				return;
			}

			if (fval.length>6)
			{
				field.val(field.val().substr(0,6));
				$("#addButton").prop('disabled','disabled');
				$("#btnNext").prop('disabled','disabled');
				return;
			}

			if (ndx >= 3 && isNaN(fval[ndx]))
			{
				field.val(fval.substr(0,ndx));
				$("#addButton").prop('disabled','disabled');
				$("#btnNext").prop('disabled','disabled');
				return;
			}

			var cc = fval.charCodeAt(ndx);
			if (ndx < 3 && (cc < 65 || cc > 90))
			{
				field.val(fval.substr(0,ndx));
				$("#addButton").prop('disabled','disabled');
				$("#btnNext").prop('disabled','disabled');
				return;
			}

			if (fval.length == 6)
			{
				CheckCodeValidity();
			}
			else
			{
				$("#addButton").prop('disabled','disabled');
				$("#btnNext").prop('disabled','disabled');
			}

		});
		$("#addButton, #AddAnotherLabel").on('click', function(evt)
		{
			
			$("#codeList").css("display","block");
			var cstr = $("#codeList").html();
			var bcode = $("#bonus-code").val();
			if (bcode.length > 10)
				bcode = "FREE ENTRY";
			cstr = bcode + (cstr.length>0?", " + cstr:"");
			if (cstr.substr(0,2) == ", ")
				cstr = cstr.substr(2);
			$("#codeListHidden").val(cstr);
			$("#codeList").html(cstr);
			$("#bonus-code").prop('disabled','');
			$("#bonus-code").val("");
			$("#bonus-code").css("background-color", "white");
			$("#bonus-code").focus();
			$("#addButton").prop('disabled','disabled');			
			$("#bonus-code").prop("placeholder", "Enter Another Code");
			$("#btnNext").prop('disabled','');
		});
		
		$("#email").on('change', function(evt)
		{
			CheckEmailValidity();
			$("#codeListHidden").val('');
			$("#codeList").html('');

		});
		
	});

	function CheckEmailValidity()
	{
		if ($("#regForm").valid() == false)
		{
			validator.focusInvalid();
			$("#email").val("");
			return false;
		}
		isCheckingFreebee = true;
		$("#regForm").prop('disabled', true);
		$.ajax(
		{
				type: "POST",
				url: "/<?php echo $g_WebServerFolder ?>/validate-free-entry.php",
				data: {"email":$("#email").val() },
				success: function(msg)
				{
					$("#regForm").prop('disabled', false);
					isCheckingFreebee = false;
					result = msg.split(":");
					
					if (result[0] == "valid")
					{
						//$("#btnNext").prop('disabled','');
						//$("#btnNext").focus();
						$("#bonus-code").val("YOU QUALIFY FOR 1 FREE ENTRY");
						$("#addButton").prop('disabled','');
						$("#addButton").focus();
						$("#email").css('background-color', 'white');
					}
					else
					{
						$("#bonus-code").prop('disabled','');
						$("#bonus-code").prop("placeholder", "Enter Code");
						$("#bonus-code").focus();
					}
				}
		});

		return false;
  }
	

	/*
			We need to check all codes when each new code is added so that they don't
			add 2 free codes when they are only permitted to have 1.
			If we check after they hit "submit", then the error message
			will be a confusing UI experience.
	*/
	function CheckCodeValidity()
	{
		if ($("#codeListHidden").val().indexOf($("#bonus-code").val()) >= 0)
		{
			isCodeValid = false;
			var aaa = $("#bonus-code");
			$("#bonus-code").css('background-color', '#ffeeee');
			$("#bonus-code").focus();
			aaa.val(aaa.val().substr(0, aaa.val().length - 1));
			return;
		}
		isCheckingValidity = true;
		var result = $.ajax(
		{
				type: "POST",
				url: "/<?php echo $g_WebServerFolder ?>/validate-coupon.php",
				data: {"bonus-code":$("#bonus-code").val().trim(), "email":$("#email").val() },
				success: function(msg)
				{
					isCheckingValidity = false;
					result = msg.split(":");
					
					if (result[0] == "valid")
					{
						if (result[1] == 0)
						{
							valid = true;
						}
						else
						{
							if (result[1] == "free")
							{
								// echo "valid:free:$count:$intLimitUsers";
								curCount = parseInt(result[2]);
								curLimit = parseInt(result[3]);
								newCount = freeCount + curCount + 1;
								if (newCount > curLimit)
									valid = false;
								else
								{
									freeCount++;
									valid = true;
								}
							}
						}
					}
					else
					{
						valid = false;
					}
					//alert(valid + " with " + msg);
					//return;
					
					if (valid)
					{
						$("#bonus-code").css('background-color', '#eeffee');
						isCodeValid = true;
						$("#addButton").prop('disabled','');
						$("#btnNext").prop('disabled','');
						$("#btnNext").focus();
					}
					else
					{
						isCodeValid = false;
						var aaa = $("#bonus-code");
						$("#bonus-code").css('background-color', '#ffeeee');
						$("#bonus-code").focus();
						$("#addButton").prop('disabled','disabled');
						$("#btnNext").prop('disabled','disabled');
						aaa.val(aaa.val().substr(0, aaa.val().length-1));
					}
				},
				fail: function(msg)
				{
					isCodeValid = false;
					$("#bonus-code").css('background-color', '#ffeeee');
					$("#bonus-code").focus();
					$("#addButton").prop('disabled','disabled');
					$("#btnNext").prop('disabled','disabled');
					isCheckingValidity = false;
				}
		});
	}

</script>

	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="regForm" class="form" enctype="multipart/form-data" >
		<input type="hidden" id="codeListHidden" name="codeListHidden">
		<header>
		</header>
		<main class="container">
			<?php 
				if ($strValidationB) 
				{
					echo '<div class="strValidationB">'.$strValidationB.'</div>';
				}
				if ($strValidation) 
				{
					echo '<div class="strValidation">'.$strValidation.'</div>';
				} ?>
			
			<table class="centerContent span10 vMiddle" id="formTable">
				<tr style="height: 50px">
					<td colspan="2" style="font-size: 28px;text-align:center;">
						<div id="codeList"></div>
					</td>
				</tr>
				<tr>
					<td width="200px">
						<label for="email">EMAIL:</label>
					</td>
					<td>
						<input type="email" name="email" id="email" placeholder="ENTER YOUR EMAIL ADDRESS" value="<?php if ($p_email) echo $p_email; ?>" required>		
					</td>
				</tr>
<!--				<tr>
					<td colspan="2">
						<label id="email-error" class="error" for="email"></label>
					</td>
				</tr> -->
				<tr>
					<td>
						<label for="bonus-code">CODE: </label>
					</td>
					<td>
						<table style="width:100%">
						<tr><td><input type="text" name="bonus-code" id="bonus-code" placeholder="6 DIGIT CONTEST CODE" disabled value=""></td>
						<td><button id="addButton" type="button" disabled="disabled" class="button buttonGreen" style="width:135px;margin-left: 20px;">Add</button></td><tr></table>
					</td>
				</tr>
				<tr>
				<td  colspan="2" style="text-align:center;padding-bottom: 40px;text-align:right;">&nbsp;
					</td>
				</tr>
				<!--<tr style="">
					<td colspan="2" style="text-align:center;padding-bottom: 40px;text-align:right;">
						<label style="display:inline-block;" id="AddAnotherLabel">Have another entry code? <span style="color:#77b14b; vertical-align: initial;">Tap here to add it!</span></label>
					</td>
				</tr>-->
<!--				<tr>
					<td colspan="2">
						<label id="bonus-code-error" class="error" for="bonus-code"></label>
					</td>
				</tr> -->
				<tr>
					<td colspan="2">
					
					</td>
				</tr>				
			</table>			
		</main>		
		
		<footer class="clearfix">
		<div class="span2 column">
			<a href='index.php' class='button home homebutton'>HOME</a>
			</div>
			<div class="rulesnregs span8 column">
				<a href="#rules" class="fancybox" >CONTEST RULES AND REGULATIONS</a>
			</div>
			<div class="span2 column2">
						<input type="submit" value="NEXT" id="btnNext" name="submit" class="button buttonGreen" style="width:135px;" id="next" disabled="disabled">	
			</div>
				<div id="rules">
					<?php include('rules.php') ?>
				</div>
			
		</footer>
	</form>
</body>
</html>