<?php

session_start();
require_once("functions.php");

if(isset($_POST["username"]) && !empty($_POST["username"]) && isset($_POST["password"]) && !empty($_POST["password"])){
	//setcookie("username",$_POST["username"], time()*60*60*24*365);
	//setcookie("password",$_POST["password"], time()*60*60*24*365);
	$username = $_POST["username"];
	$password = $_POST["password"];
	$ip_address = $_SERVER['REMOTE_ADDR'];
	$array_login = array('username'   => $username,'password'   => $password );
	$sql_login ="select * FROM clienti WHERE username=:username and password=:password  and stato = 1 LIMIT 1";
	list($status_login,$contenuto_login,$nrows_login) = read_db_pdo($sql_login,$array_login);
	$stato_cliente = $contenuto_login[0]["stato"];
	if ($nrows_login==0){
		session_destroy();
		$_SESSION = array();
		//header("Location: index.php");
	}
	if( ($status_login==1) && ($nrows_login==1) ) {
		$id_utente = (int) $contenuto_login[0]["id_cliente"];
		if($id_utente < 1 ) {
			// write_admin_user_login($username,1);
			$errori_input[] = "KO1";
			exit;
		}
		$user_logged = $contenuto_login[0]["username"];
		if($user_logged!=$username ) {
			// write_admin_user_login($username,1);
			$errori_input[] =  "KO2";
			exit;
		}
		$stato = $contenuto_login[0]["stato"];
		if($stato == 0 ) {
				$errori_input[] =  "KO2000";
			exit;
		}
		$oggi = date("d-m-Y"); 
		$server = $_SERVER['SERVER_NAME'];
		$info_utente_logged = array("username"=>$user_logged,"id_utente"=>$id_utente, "data"=>$oggi);
		$_SESSION["DAST-SERVER"]["hash_info_utente_logged"] = md5($user_logged.$oggi.$server);
		$_SESSION["DAST-SERVER"]['info_utente_logged'] = $info_utente_logged;	
	//	insert_user_last_activity_time($id_utente); exit;
		header("Location: home.php");
		exit;
	} else {
		// write_admin_user_login($username,1);
		$n_tentativi_login = check_admin_failed_login();
		if ($n_tentativi_login < 15) { 
			$errori_input[] =  "KO100";
			exit;
		}else{
			$errori_input[] =  "KO1000";
			exit;
		}
	}
	if (!empty($errori_input)) {
		foreach ($errori_input as $errore) {
			echo $errore."\n";
		}
		exit; 
	}	
exit;
}

 