<?php
require('includes/settings.php');
require('includes/mysql_connect.php');
require('includes/funcs.php');
$p_bonus_code = sanitize($_REQUEST['bonus-code']);
$p_email = sanitize($_REQUEST['email']);

//error_log($p_email);

if ($p_bonus_code == $g_TestCode)
{
	echo "valid";
	exit();
}
if ($p_bonus_code == "FREE ENTRY")
{
	echo "valid:free";
	exit();
}

if ($p_bonus_code == null || !preg_match('/^[A-Z]{3}\d{3}$/', $p_bonus_code))
{
	echo "fail";
	exit();
}

// check if code is available and get its limitations
$check_code_sql = "
	SELECT intBonusCodeID, intCodeType, intLimitUsers from ".$g_KioskBonusCodesTableName." tb
	inner join ".$g_KioskCodeTypesTableName." tt on tt.intCodeTypeID = tb.intCodeType
	where strBonusCode = '$p_bonus_code' and ynUsed = 'N'
	";

//error_log($check_code_sql);
$check_code_result = getFromDatabase($check_code_sql);
if(mysqli_num_rows($check_code_result) == 0)
{
	echo "fail:invalid";
	exit();
}

$check_fetch = mysqli_fetch_array($check_code_result);
$intBonusCodeID =  $check_fetch[0];
$intCodeTypeID =  $check_fetch[1];
$intLimitUsers =  $check_fetch[2];

if ($intLimitUsers == 0)
{
	echo "valid:0";
	exit();
}

// Check if given email exceeds user limit for code type
$check_code_sql = 'SELECT count(*) from '.$g_KioskTableName.' ktn
	inner join '.$g_KioskBonusCodesTableName.' tb on tb.intBonusCodeID = ktn.intBonusCode
	inner join '.$g_KioskCodeTypesTableName.' tt on tt.intCodeTypeID = tb.intCodeType
	where ktn.strEmail="' . $p_email . '" and tt.intCodeTypeID = ' . $intCodeTypeID
;
//error_log($check_code_sql);

//echo "<p>$check_code_sql</p>";
$check_code_result = getFromDatabase($check_code_sql);
if(mysqli_num_rows($check_code_result) == 0)
{
	echo "fail:free";
	exit();
}
$check_fetch = mysqli_fetch_array($check_code_result);
$count =  $check_fetch[0];

echo "valid:free:$count:$intLimitUsers";

?>
