<?php 
include("includes/config.php");
include("includes/func.php");
include('classes/readxml.class.php');
$Get_XML_Responce	= new read_xml;
	
	$is_forgot 	= false;
	$LoginError = "";
	$errorMsg	= "";
	
/* Section to check is longin button is clicked or forgot my password button */
	if(isset($_POST['mui'])){
		$ActionToExec = $_POST['mui'];
	}

/* Section for forgot password */
	if($ActionToExec == "sendpw") {
		
		$is_forgot = true;
		
		$forgot_email = SQLSafe($_POST['forgot_email']);
		
		if ($forgot_email == '') { $errorMsg = "Please enter your email address."; }
		
		if ($errorMsg == '') {
			
			$sql = sprintf("select CONCAT(`firstname`, ' ', `lastname`) as name, `email`, `password`
							from users 
							where `email` = '%s'", $forgot_email);
			$res =  mysql_query($sql) or die("Error: " . mysql_error());
			
			if (mysql_num_rows($res) > 0) {
				
				$row = mysql_fetch_array($res);
				
				$name 	= $row['name'];
				$email 	= $row['email'];
				$pass 	= $row['password'];
				
				/// New Pawword Genetor ///
				$new_password = "";
				$characters = array(
								"A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
								"1","2","3","4","5","6","7","8","9");
				$keys = array();
				while(count($keys) < 7) {
					$x = mt_rand(0, count($characters)-1);
					if(!in_array($x, $keys)) {
					   $keys[] = $x;
					}
				}
				
				foreach($keys as $key){
				   $new_password .= $characters[$key];
				}
				
				// Update the new password in database //
				$sql =  "Update `users` SET `password` = "."'".$new_password."'"." Where `email` = "."'".$forgot_email."'"."";
				mysql_query($sql);
	//			echo $sql;
	//			exit;
				
			// send email address
				$email_subject = $Get_XML_Responce->readXmlArrtibut('xml_login_message.xml', 'Email_Subject');
				$email_body = $Get_XML_Responce->readXmlArrtibut('xml_login_message.xml', 'Email_Text_Body');
				$email_footer = $Get_XML_Responce->readXmlArrtibut('xml_login_message.xml', 'Email_Text_Footer');
				$msg = "Dear " . $name . ",<br/><br/>"
						.$email_body. $new_password . "<br/>"
						.$email_footer;
				//	  ."Thanks<br/>Manger Inventory System";
				$msg = str_replace("\n.", "\n..", $msg);
				$to = "$name <$email>";//$arr[0]."<".$arr[2].">";
				$subject = $email_subject;
				//$subject = "Your requested password";
				// To send HTML mail, the Content-type header must be set
				$headers  = 'MIME-Version: 1.0' . "\r\n";
				$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
				
				if (mail($to, $subject,	$msg, $headers))
					$errorMsg = "Email containing password sent to you.";
				else 
					$errorMsg = "Error while sending an email.";
					
			} else {
				
				$errorMsg = "Entered email address not found.";
			}
			
		}
	}

/* Section to check email and password: if true then create sessions and redirect it to main page */
if($ActionToExec == "login")
{ 	
	$AdminUN 		= trim($_POST['AdminUN']);
	$AdminPW 		= trim($_POST['AdminPW']);
	$IsLogin 		= false;
	$LoginError 	= "";
		
	if (($AdminUN == "" || $AdminPW == ""))
	{
		$LoginError = "Invalid login. Email and Password required.";
	
	} else if($AdminUN != "" && $AdminPW != "" ){
		
		$IsLogin = true;
		$sql ="select * from users where username='".$AdminUN."' and password='".$AdminPW."'";
		$res = mysql_query($sql);
		$row = mysql_fetch_array($res);
			
			if($row == "")
			{
				$LoginError = "Invalid login, please try again.";
			
			}else {
			
				if($AdminPW == $row['password'])
				{
					$_SESSION['id']					= $row['id'];
					$_SESSION['firstname']			= $row['firstname'];
					$_SESSION['lastname'] 			= $row['lastname'];
					$_SESSION['email'] 				= $row['email'];
					$_SESSION['username']			= $row['username'];
					
					if($row['usertypeid'] == '1')
					{ 
						$_SESSION['usertype']		= 'Admin'; 
					}else{
						$_SESSION['usertype']		= 'User';
					}
					
					redirect("index");	
				
				} else {
							$LoginError = "Invalid login.";
				}
			}	

	}
}

	if ($_SESSION['re_login'] == 'yes') {
		$LoginError = "Your session has been expired";
		$_SESSION['re_login'] = '';	
	}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Equivalenza</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascripts/jquery.min.js"></script>
<script language="JavaScript">
	
	$(document).ready( function () {

		$("#btn_cancel").click(function () {

			$("#forgot_pw_sec").hide();
			$('#login_sec').fadeIn();
			
		});
	});
	
	function LoadCookies(){
		start();
		GetCookie("AdminUN");	
	}

	function GetCookie(Name) {
		var search = Name + "="
		var NameLength = Name.length
		var NameType = Name.substr(NameLength - 2);
		if (document.cookie.length > 0) {
			offset = document.cookie.indexOf(search)
			if (offset != -1) {
				offset += search.length
				end = document.cookie.indexOf(";", offset)
				if (end == -1) {
					end = document.cookie.length
				}
				var CookieValue = unescape(document.cookie.substring(offset, end))
				if (CookieValue != "") {
					if (NameType == "UN") {
						document.AdminLogin.AdminUN.value = CookieValue
						document.AdminLogin.RememberUN.checked = true
					}
					if (NameType == "PW") {
						//document.AdminLogin.AdminPW.value = CookieValue
						//document.AdminLogin.RememberPW.checked = true
					}
				}
				// Used by Netscape
				else {
					if (NameType == "UN") {
						document.AdminLogin.AdminUN.value = ""
						document.AdminLogin.RememberUN.checked = false
					}
					if (NameType == "PW") {
						//document.AdminLogin.AdminPW.value = ""
						//document.AdminLogin.RememberPW.checked = false
					}
				}
			}
			// Used by IE
			else {
				if (NameType == "UN") {
					document.AdminLogin.AdminUN.value = ""
					document.AdminLogin.RememberUN.checked = false
				}
				if (NameType == "PW") {
					//document.AdminLogin.AdminPW.value = ""
					//document.AdminLogin.RememberPW.checked = false
				}
			}
		}
	}


function SetCookie(CookieName,CookieValue) 
	{
		var today = new Date()
		var expires = new Date()
		var CookieValue = escape(CookieValue)
		expires.setTime(today.getTime() + 1000*60*60*24*365)
		document.cookie = CookieName + "=" + CookieValue + "; expires=" + expires.toGMTString()
	}

function ForgotPW() 
	{
		/*document.AdminLogin.mui.value ='sendpw';
		document.AdminLogin.submit();*/
		
		$('#login_sec').hide();
		$("#forgot_pw_sec").fadeIn();
		
	}
	
function SubmitLogin() 
	{
		if (document.AdminLogin.RememberUN.checked == true) {
			var CookieName = "AdminUN";
			var CookieValue = document.AdminLogin.AdminUN.value;
			SetCookie(CookieName,CookieValue);
		}
		else {
			var CookieName = "AdminUN";
			var CookieValue = "";
			SetCookie(CookieName,CookieValue);
		}
			var CookieName = "AdminPW";
			var CookieValue = "";
			SetCookie(CookieName,CookieValue);
		document.AdminLogin.submit()
	}

 function start() {

        var time = new Date()
        var hours = time.getHours()
        var minutes = time.getMinutes()
        minutes = ((minutes < 10) ? "0" : "") + minutes
        var seconds = time.getSeconds()
        seconds = ((seconds < 10) ? "0" : "") + seconds
        var clock = '';
        if (hours == 12) {
            clock = hours + ":" + minutes + ":" + seconds + " PM";
        }
        else if (hours > 12) {
            hours = hours - 12;
            clock = hours + ":" + minutes + ":" + seconds + " PM";
        }
        else {
            clock = hours + ":" + minutes + ":" + seconds + " AM";
        }
        document.getElementById("dv").innerHTML = clock
        timer = setTimeout("start()", 1000)
    }
</script>
</head>

<body onLoad="LoadCookies()">

<div id="siteHeader">
	<div id="innerHeaderContent">
    <div id="headerContent">
        	<div id="logo"> 
            	<a href="#"><img src="images/logo.png" /></a>
        	</div>
            <div id="headerRightsideContent">
            	<div>  <a href="login.php">LogIn</a></div>
                <div class="time" id="dv"></div>
            </div>
    </div>
    <div id="navigationPanel">
    	
    </div>
    </div>
</div>

<div id="mainPanel">
	<h2>Admin Panel</h2>
    <h6></h6>
    <div class="session">
    	 <div class="header"><h3>Sign In</h3></div>
         <!-- login form start -->
         <div class="content" id="login_sec" style="display:<?php if ($is_forgot == true) print 'none;'; ?>">
            
            <span class="text1Col"><?php echo $LoginError ?>&nbsp;</span>
            
            <form name="AdminLogin" method="post" action="" onSubmit='return SubmitLogin()'>
                <input type='hidden' name='mui' value='login' id="mui">
            
            <div class="loginForm">
            <table width="100%" id="tabling" cellpadding="0" cellspacing="0">
    	<tr>
        	<td class="col1"><span class="blue">User Name:</span></td>
            <td class="col2"><input class="txtfield" type="text" onblur="if (this.value == '') { this.value='Type your email address here!'; }" onfocus="if (this.value == 'Type your email address here!') { this.value=''; }" value="Type your email address here!" name="AdminUN"></td>
        </tr>
        <tr>
        	<td class="col1"><span class="blue">Password:</span></td>
            <td class="col2"> <input class="txtfield2" type="password" onblur="if (this.value == '') { this.value='Type your Password here!'; }" onfocus="if (this.value == 'Type your Password here!') { this.value=''; }" value="Type your Password here!" name="AdminPW"><a href="#" onClick='ForgotPW();'><span class="blue"> Forgot your Password? </span></a> </td>
        </tr>
       <!-- <tr>
        	<td class="col1"><h4><input name="RememberUN" type="checkbox" value="yes" /> Remember Me</h4></td>
            
            <td class="col2" colspan="2"></td>
        </tr>           	           -->
         <tr>
         	<td class="col1"></td>
            <td class="col3"><input type="submit" value="Sign In" name="subm" id="subm" class="form_button" /></td>
         </tr>
   </table>         
            </div>
               
                      
               </form>     
        </div> 
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->        
         
           <!-- login form start -->
         <div class="content" id="forgot_pw_sec" style="display:<?php if ($is_forgot == false) print 'none;'; ?>">
            
           <span class="text1Col"><?php echo $errorMsg ?>&nbsp;</span>
            
            <form name="frm_forgot_pw" id="frm_forgot_pw" method="post" action="">
                <input type='hidden' name='mui' value='sendpw' id="mui">
            
            <div class="loginForm">
             <table  width="100%" id="tabling" cellpadding="0" cellspacing="0">
    		<tr>
        	<td class="col1"><span class="blue">Enter your email:</span></td>
            <td class="col2"><input size="25" class="txtfield" name="forgot_email" id="forgot_email" value=""></td>
        </tr>
                      
          	 <tr>
              	<td class="col1"> </td>
                <td class="col3">
                	<!--<a href="#" id="btn_cancel2" >Send Password</a> -->
                    <input type="submit" class="form_button"  value="Send Password">&nbsp;
                    <a href="#" id="btn_cancel" >Cancel</a>
               </td>
         	 </tr>
             </table>
            </div>
               </form>     
            <!-- End login form -->
            
         </div>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->

    </div>
    
</div>

</body>
</html>