<?php
$skip_permissions = true;
include_once(__DIR__."/core.php");

$op = filter('op');
$username = filter('username');

// LOGIN
switch ($op) {
	case 'login' :
        $password = filter('password');
		if ($dbo_state == true) {
			$query = "SELECT *, (SELECT nome FROM zz_gruppi WHERE id=idgruppo) AS gruppo FROM zz_utenti WHERE username=" . prepare($username) . " AND password=MD5(" . prepare($password) . ")";
			$rs = $dbo->fetchArray($query);

			$cont = count($rs);
			if($cont == 0) {
				$rs[0]['idutente'] = 0;
				$rs[0]['enabled'] = 0;
				$rs[0]['gruppo'] = 0;
			}

			logaccessi($rs[0]['idutente'], $username, $password, sizeof($rs), $rs[0]['enabled'], $rs[0]['gruppo']);

			// loggo gli accessi
			if ($cont <= 0) {
				array_push($_SESSION['errors'], _("Autenticazione fallita!"));
			}

			else if ($rs[0]['enabled'] == 0) {
				array_push($_SESSION['errors'], _("Utente non abilitato!"));
			}

			else {
				
				// registo la chiave per mobile
				
				$query_mobile="UPDATE zz_utenti SET chiave_mobile=MD5(CONCAT('".$username."', MD5('".$password."'))) WHERE idutente='".$rs[0]['idutente']."'";
				$dbo->query($query_mobile);
				
				
				if (isset($_POST['keep_alive']) && $_POST['keep_alive'] == 'on') {
					$_SESSION['keep_alive'] = true;
				}

				$_SESSION['idutente'] = $rs[0]['idutente'];
				$_SESSION['idanagrafica'] = $rs[0]['idanagrafica'];
				$_SESSION['username'] = $rs[0]['username'];
				$_SESSION['gruppo'] = $rs[0]['gruppo'];
				
			
				
				// ricerco impostazione utente
				$rs_profilo = $dbo->fetchArray("SELECT profilo_pannello  FROM zz_utenti  WHERE idutente=\"".$_SESSION['idutente']."\"");	
				$_SESSION['profilo_pannello']=$rs_profilo[0]['profilo_pannello'];
				
				
				
				if ($rs[0]['gruppo'] == 'Amministratori') {
					$_SESSION['is_admin'] = true;
				}

				// Auto backup del database giornaliero
				if (get_var("Backup automatico")) {
					$folders = glob($backup_dir . '*');
					$regexp = '/' . date('Y\-m\-d') . '/';

					// Controllo se esiste già un backup zip o folder creato per oggi
					if (! empty($folders)) {
						$found = false;
						foreach ($folders as $folder) {
							if (preg_match($regexp, $folder, $matches)) {
								$found = true;
							}
						}
					}

					if ($found) {
						array_push($_SESSION['infos'], _("Backup saltato perché già esistente!"));
					}
					else if (do_backup()) {
						array_push($_SESSION['infos'], _("Backup automatico eseguito correttamente!"));
					}
					else if ($backup_dir == "") {
						array_push($_SESSION['errors'], _("Non è possibile eseguire i backup poichè la cartella di backup non esiste!!!"));
					}
					else if (! file_exists($backup_dir)) {
						if (mkdir($backup_dir)) {
							array_push($_SESSION['infos'], _("La cartella di backup è stata creata correttamente."));
							do_backup();
						}
						else {
							array_push($_SESSION['errors'], _("Non è stato possibile creare la cartella di backup!"));
						}
					}
				}
			}
		}
		break;

	case 'logout' :
		logout();
		redirect("index.php", "php");
		exit();

		break;
}

if (isUserAutenticated() && isset($dbo) && $is_db_installed) {
	// Redirect al primo modulo su cui l'utente ha accesso se l'utente è già loggato
	if (isAdminAutenticated()) $q = "SELECT id, module_dir, options FROM zz_modules WHERE parent='0' AND enabled='1' ORDER BY `order` ASC";
	else $q = "SELECT id, module_dir, options FROM zz_modules WHERE parent='0' AND enabled='1' AND id IN (SELECT idmodule FROM zz_permessi WHERE idgruppo=(SELECT id FROM zz_gruppi WHERE nome=" . prepare($_SESSION['gruppo']) . ") AND permessi IN ('r', 'rw') ) ORDER BY `order` ASC";

	$rs = $dbo->fetchArray($q);

	if (count($rs) != 0) {
		for($i = 0; $i < sizeof($rs); $i ++) {
			if ($rs[$i]['options'] != '') {
				redirect($rootdir . "/controller.php?id_module=" . $rs[0]['id'], "js");
				exit();
			}
		}
	}
	else if (! isAdminAutenticated() && $op != 'logout') array_push($_SESSION['errors'], _("L'utente non ha nessun permesso impostato!"));
}

echo '<!DOCTYPE html>
<html class="bg-black">
	<head>
		<meta charset="UTF-8">
		<title>' . _("GEST366") . ' ' . _("Login") . '</title>
		<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
		<link href="' . $css . '/AdminLTE.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/_all-skins.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/bootstrap.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/font-awesome.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/jquery-ui.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/jquery.steps.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/parsley.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/style.min.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link href="' . $css . '/switch.css?v=' . $version . '" rel="stylesheet" type="text/css">
		<link rel="shortcut icon" href="assets/img/favicon.ico">		
		<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
		<!-- WARNING: Respond.js doesn\'t work if you view the page via file:// -->
		<!--[if lt IE 9]>
          <script src="' . $js . '/html5shiv.min.js?v=' . $version . '"></script>
          <script src="' . $js . '/respond.min.js?v=' . $version . '"></script>
        <![endif]-->

		<script src="' . $js . '/jquery.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/jquery-ui.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/jquery.steps.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/js.cookie.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/bootstrap.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/jquery.ui.shake.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/parsley.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/i18n/parsleyjs/it.min.js?v=' . $version . '"></script>
		<script src="' . $js . '/app.min.js?v=' . $version . '"></script>
	</head>
	<body class="hold-transition login-page">
		<div class="wrapper">';

include ($docroot . "/update/update_checker.php");
$is_db_installed = $dbo->fetchNum("SHOW TABLES LIKE 'zz_modules'");

// Controllo se è una beta e in caso mostro un warning
if (strpos($version, "beta") !== false) {
	echo '
			<script>$(document).ready( function(){ $("#beta").addClass("in"); });</script>
			<div id="beta" class="alert alert-warning alert-dismissable pull-right fade">
				<i class="fa fa-warning"></i>
				<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
				<b>' . _("Attenzione!") . '</b> ' . _("Stai utilizzando una versione <b>non stabile</b> di Gestionale 360.") . '
			</div>';
}

if (sizeof($_SESSION['infos']) != 0) {
	echo '
			<div class="box box-center box-success box-solid text-center">
				<div class="box-header with-border">
					<h3 class="box-title">' . _("Informazioni") . '</h3>
				</div>
				<div class="box-body">';
	for($i = 0; $i < sizeof($_SESSION['infos']); $i ++) {
		echo '
					<p><i class="fa fa-check"></i> ' . $_SESSION['infos'][$i] . '</p>';
	}
	echo '
				</div>
			</div>';
}

if (sizeof($_SESSION['errors']) != 0) {
	echo '
			<div class="box box-center box-danger box-solid text-center">
				<div class="box-header with-border">
					<h3 class="box-title">' . _("Errori") . '</h3>
				</div>
				<div class="box-body">';
	for($i = 0; $i < sizeof($_SESSION['errors']); $i ++) {
		echo '
					<p><i class="fa fa-warning"></i> ' . $_SESSION['errors'][$i] . '</p>';
	}
	echo '
				</div>
			</div>
			<script> $(document).ready( function(){ $(".login-box").shake(); }); </script>';
}

unset($_SESSION['infos']);
unset($_SESSION['errors']);

// Cerco logo e descrizione

	$query_logo="Select * from zz_utenti_logo";
	$rs_logo = $dbo->fetchArray($query_logo);
	$file_logo=$rootdir."/assets/img/".$rs_logo[0]['immagine'];	
	$descr_logo=$rs_logo[0]['descrizione'];	
	$_SESSION['nome_gestonale360'] = $descr_logo;

echo '
			<form action="?op=login" method="post" class="login-box box">

					<div class="box-header with-border text-center">
						<img src="' . $file_logo . '" class="img-thumbnail" alt="' . _("") . '">
					</div>

				<!-- /.box-header -->
				<div class="login-box-body box-body">
					<div class="form-group input-group">
						<span class="input-group-addon"><i class="fa fa-user"></i> </span>
						<input type="text" name="username" autocomplete="off" class="form-control" placeholder="' . _("Nome utente") . '"';
if(isset($username)) echo ' value="' . $username . '"';
echo'>
					</div>
					<div class="form-group input-group">
						<span class="input-group-addon"><i class="fa fa-lock"></i> </span>
						<input type="password" name="password" autocomplete="off" class="form-control" placeholder="' . _("Password") . '">
					</div>
					<div class="form-group">
						<input type="checkbox" name="keep_alive"';
if (filter("keep_alive") != null) echo ' checked';
echo '/> ' . _("Mantieni attiva la sessione") . '
					</div>
				</div>
				<!-- /.box-body -->
				<div class="box-footer">
					<button type="submit" id="login" class="btn btn-danger btn-block">' . _("Accedi") . '</button>
				</div>
				<!-- box-footer -->
			</form>
			<!-- /.box -->

		</div>
		<script>
		$(document).ready( function(){
			$("#login").click(function(){
				$("#login").text(\'';
if (isset($is_db_installed) && $is_db_installed == 1 && get_var("Backup automatico")) echo _("Backup automatico in corso...");
else echo _("Autenticazione...");
echo '\');
			});

			if( $(\'input[name=username]\').val() == \'\' ){
				$(\'input[name=username]\').focus();
			}
			else{
				$(\'input[name=password]\').focus();
			}
		});
		</script>
	</body>
</html>';

?>
