<?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']))
{
	// $formHide = false;
	$boolValidate = true;
	$strValidation = $strValidationB = '';
	
	$p_email = sanitize($_POST["email"]);
	$p_bonus_code = sanitize($_POST['bonus-code']);
	$p_bonus_code_list = sanitize($_POST['codeListHidden']);
	
	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;
		
	$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 == null || !preg_match('/^[A-Z]{3}\d{3}$/', $p_bonus_code))
	if ($p_bonus_code_list == null || !preg_match('/^([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 
			}
			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;

					$bonus_sql = "UPDATE ".$g_KioskBonusCodesTableName." set ynUsed = 'Y', intUsedBy=" .$insertID. "  where intBonusCodeID = '$intBonusCode'";
					$bonus_result = getFromDatabase($bonus_sql);

					mysqli_commit($dbc);
					//header('Location:contest_page3.php');
				}
				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;
	$(document).ready(function()
	{
		setTimeout(function(){$("#bonus-code").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));
				return;
			}

			if (ndx >= 3 && isNaN(fval[ndx]))
			{
				field.val(fval.substr(0,ndx));
				return;
			}

			var cc = fval.charCodeAt(ndx);
			if (ndx < 3 && (cc < 65 || cc > 90))
			{
				field.val(fval.substr(0,ndx));
				return;
			}

			if (fval.length == 6)
			{
				CheckValidity();
			}

		});
		$("#addButton, #AddAnotherLabel").on('click', function(evt)
		{
			$("#codeList").css("display","block");
			var cstr = $("#codeList").html();
			cstr = $("#bonus-code").val() + (cstr.length>0?", " + cstr:"");
			if (cstr.substr(0,2) == ", ")
				cstr = cstr.substr(2);
			$("#codeListHidden").val(cstr);
			$("#codeList").html(cstr);
			$("#bonus-code").val("");
			$("#bonus-code").css("background-color", "white");
			$("#bonus-code").focus();
			$("#addButton").prop('disabled','disabled');			
		});

		$("#email").on('focus', function(evt)
		{
			if (!isCodeValid)
				$("#bonus-code").focus();
		});
	});
	
	function CheckValidity()
	{
		isCheckingValidity = true;
		var result = $.ajax(
		{
				type: "POST",
				url: "/kioskspeterpond/validate-coupon.php",
				data: {"bonus-code":$("#bonus-code").val()},
				success: function(msg)
				{
					isCheckingValidity = false;
					if (msg == "valid")
					{
						$("#bonus-code").css('background-color', '#eeffee');
						isCodeValid = true;
						$("#addButton").prop('disabled','');
						$("#email").focus();
					}
					else
					{
						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));
					}
				},
				fail: function(msg)
				{
					isCodeValid = false;
					$("#bonus-code").css('background-color', '#ffeeee');
					$("#bonus-code").focus();
					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>
			<a href='index.php' class='button home'>HOME</a>
		</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>
					<td colspan="2" style="font-size: 68px">
						<div style="overflow: scroll; width: 100%; max-height: 300px; text-align: center" id="codeList"></div>
					</td>
				</tr>
				<tr>
					<td>
						<label for="bonus-code">ENTRY CODE: </label>
					</td>
					<td>
						<table style="width:100%">
						<tr><td><input type="text" name="bonus-code" id="bonus-code" value="<?php if ($p_bonus_code) echo $p_bonus_code; ?>" style="width:553px"></td>
						<td><button id="addButton" type="button" disabled="disabled" class="button" style="width:135px;margin-left: 20px;">Add</button></td><tr></table>
					</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:yellow; 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 width="200px">
						<label for="email">EMAIL:</label>
					</td>
					<td>
						<input type="email" name="email" id="email" 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 colspan="2">
					<div class="span12 textRight column">
						<input type="submit" value="NEXT" name="submit" class="button" style="width:135px;">	
					</div>
					</td>
				</tr>				
			</table>			
		</main>		
		
		<footer class="clearfix span11 centerContent">
			<div class="span5 column">
				<a href="#rules" class="fancybox" >CONTEST RULES AND REGULATIONS</a>
				<div id="rules">
					<?php include('rules.php') ?>
				</div>
			</div>
		</footer>
	</form>
</body>
</html>