<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

$no_visible_elements=true;
require "../_container/container_top.php";
require_once ('business/ReservationMgr.php');
require_once ('business/MailMgr.php');
require_once ('business/UserMgr.php');
require_once("config/Tagger.php");

if (!isset($action)) {
	$action = getPost('action');
}

if (!empty($action) && $action == "SIGN_OUT" && isset($session->connected)){
	Logger::info(' action: [' . $action . ']');
	$sessionManager->destroy();
	$statusClass = "info";
	$status = $tr->translate("msgDisconnect");
}

if (!empty($action) && $action == "SIGN_IN"){
	Logger::info(' action: [' . $action . ']');
	$userMgr = new UserMgr();
	$username = getPost("username");
	$password = getPost("password");
	$res = $userMgr->userLogin($username, $password);

	// Login OK:	
	if ($res == 1) {
		$session->connected = $username;
		$session->userDisplayName = $username;
		Logger::info('Login is successfuly');
		$statusClass = "info";
		$status = "Successfully Connected-as";

		$mailMgr = new MailMgr();
		$tagger = new Tagger();
		$mail = $mailMgr->getMail(11);
		if (isset($mail) && !empty($mail[0]->enable)){
			// Logger::debug(' --> mail before tagging: ' . print_r($mail, true));
			$tagger->setReservationId(0);
			$mail[0]->from = $config['renter_email'];
			$mail[0]->to = $tagger->tag($mail[0]->to);
			$mail[0]->cc = $tagger->tag($mail[0]->cc);
			$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
			$mail[0]->subject = $tagger->tag($mail[0]->subject);
			$mail[0]->content = $tagger->tag($mail[0]->content);
			// Logger::debug(' --> mail after tagging: ' . print_r($mail, true));
			include_once ('config/Mailer.php');
			$m = new Mailer($config);
			$r = $m->sendMail($mail);
			if (!$r) {
				$msgType = "error";
				$msg = $tr->translate("msgMailError");
			}
		}

		$usr = $userMgr->getUsers($username);
		$session->userId = $usr[0]->user_id;
		$session->userEmail = $usr[0]->email;

		// Check for update
		$url = strtolower('http://cogites.com/ereserv/update/version_' . VERSION_TYPE . '.php');
		try{
			$response = Zend\Http\ClientStatic::post($url, array(
				'lic' => VERSION_TYPE,
				'ver' => VERSION_NUMBER,
				'lng' => $config['language'],
				'srv' => $_SERVER['SERVER_NAME'],
				'url' => (isset($_SERVER['SCRIPT_URI'])) ? $_SERVER['SCRIPT_URI'] : "",
				'add' => $_SERVER['SERVER_ADDR'],
			));
			if ($response->isSuccess()) {
				$session->upd = $response->getBody();
				Logger::debug('Check for Update Message: ' . $session->upd);
			}
		} catch (Zend\Http\Client\Adapter\Exception\RuntimeException $e) {
			// echo $e->getMessage();
			Logger::err('Check for Update FAILED: ' . $e->getMessage());
		}
		Logger::info('Server details: ' . print_r($_SERVER, true));
		Logger::info('User details: ' . print_r($usr, true));
		Logger::info('Ready to redirect to: ' . CONTEXT_ROOT_RESS . '/front/admin');

		header("Location: " . CONTEXT_ROOT_RESS . '/front/admin');
		exit;
	}
	// user dosnt exists
	if ($res == -1) {
		Logger::err('UserID not found: ' . $username);
		$statusClass = "error";
		$status = $tr->translate("msgBadUser");
	}
	// user not yet validated
	if ($res == -2) {
		Logger::warn('UserID is disabled or has not been validated: ' . $username);
		$statusClass = "warning";
		$status = $tr->translate("msgUserDisabled");
	}
	// user / password does not match
	if ($res == 0) {
		Logger::err('UserID and Password does not match the DB: ' . $username);
		$statusClass = "error";
		$status = $tr->translate("msgBadPassword");
	}
}

if (!empty($action) && $action == "RECOVER_PWD"){
	Logger::info(' action: [' . $action . ']');
	$email = getPost("email");
	$userMgr = new UserMgr();
	$res = $userMgr->getUserByEmail($email);
	if (count($res) == 1) {
		$statusClass = "info";
		$status = $tr->translate("msgResetSent");
		$resetid = md5(time());
		$res = $userMgr->setResetId($res[0]->user_id, $resetid);
				$mail[0]->from = $config['renter_email'];
				$mail[0]->to = $email;
				$mail[0]->subject = "Demande de changement de mot de passe";
				$mail[0]->content = "Une nouvelle demande a été faite.<br><br>";
				$mail[0]->content .= "URL: " . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . "?id=" . $resetid;
				include_once ('config/Mailer.php');
				$m = new Mailer($config);
				$r = $m->sendMail($mail);
				if (!$r) {
					$msgType = "error";
					$msg = $tr->translate("msgMailError");
				}
	}else{
		$statusClass = "error";
		$status = $tr->translate("msgEmailNotFound");
	}
}

if (!empty($action) && $action == "RESETPWD"){
		Logger::info(' action: [' . $action . ']');
		$userMgr = new UserMgr();
		$res = $userMgr->changePassword(getPost("userid"), getPost("password"));
		if ($res == 1) {
			$userMgr->clearResetId(getPost("userid"));
			$statusClass = "success";
			$status = $tr->translate("msgResetIdSuccess");
		}else{
			$statusClass = "error";
			$status = $tr->translate("msgResetIdError");
		}
}
$resetid = (isset($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : "";
if (!empty($resetid)){
	$userMgr = new UserMgr();
	$res = $userMgr->getUserByResetId($resetid);
	if(count($res) == 1) {
		$username = $res[0]->username;
		$userid = $res[0]->user_id;
	}else{
		$statusClass = "error";
		$status = $tr->translate("msgResetIdNotFound");
	}	
}

?>
			<div class="row-fluid hide" id="loginDiv">
				<div class="span4 offset4 login-box center">
					<div class="signin">
			<div class="wrapper">
			<?php if(DEMO_MODE) { ?>
				<div class="alert alert-info">
					<strong>Login: admin<br>Mot de passe: admin</strong>
				</div>
			<?php } ?>
			<div class="ribbon-wrapper-green"><div class="ribbon-green"><?php echo VERSION_TYPE; ?></div></div>
			<?php if (!empty($status)) { ?>
			<div class="alert alert-<?php echo $statusClass; ?>">
				<button type="button" class="close" data-dismiss="alert"></button>
				<strong><?php echo $status; ?></strong>
			</div>
			<?php } ?>

			<div id="logo">
				<div class="inline">
					<img src="<?php echo CONTEXT_ROOT_RESS;?>/styles/img/ereserv.jpg" alt="eReserv Logo">
				</div>
			</div>
			<div class="tab-content">
			<?php if (empty($resetid) || empty($username)){ ?>
				<div id="login" class="tab-pane active">
					<form action="login.php" accept-charset="utf-8" method="post">
						<input type="hidden" id="action" name="action" value="SIGN_IN">
						<div class="control-group">
							<div class="controls">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-user"></i></span><input autofocus id="username" name="username" type="text" placeholder="<?php echo $tr->translate("phUsername"); ?>" required="required">
									<div></div>
								</div>
							</div>
							<div class="controls">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-lock"></i></span><input id="password" name="password" type="password" placeholder="<?php echo $tr->translate("phPassword"); ?>" required="required">
									<div></div>
								</div>
							</div>
						</div>
						<p class="center span5">
						<button class="btn btn-primary" type="submit"><?php echo $tr->translate("btnSignIn"); ?></button>
						</p>
					</form>
					<div class="inline">
						<span><a class="muted" href="#forgot" data-toggle="tab"><?php echo $tr->translate("thRecover"); ?></a></span>
					</div>
				</div>
				<div id="forgot" class="tab-pane">
					<form action="login.php" accept-charset="utf-8" method="post">
						<input type="hidden" id="action" name="action" value="RECOVER_PWD">
						<div class="control-group">
							<div class="controls">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-envelope"></i></span><input id="email" name="email" type="email" placeholder="<?php echo $tr->translate("phEmail"); ?>" required="required">
									<div></div>
								</div>
							</div>
						</div>
						<p class="center span5">
							<button class="btn btn-primary" type="submit"><?php echo $tr->translate("btnRecover"); ?></button>
						</p>
					</form>
					<div class="inline">
						<span><a class="muted" href="#login" data-toggle="tab"><?php echo $tr->translate("thLogin"); ?></a></span>
					</div>
				</div>
				<?php }else{ ?>
				<div id="reset" class="">
					<form action="login.php" method="post">
						<input type="hidden" id="action" name="action" value="RESETPWD">
						<input type="hidden" id="userid" name="userid" value="<?php echo $userid; ?>">
						<div class="control-group">
							<div class="controls">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-user"></i></span><input id="username" name="username" type="text" value="<?php echo $username; ?>" disabled>
								</div>
							</div>
							<div class="controls">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-lock"></i></span><input id="password" name="password" type="password" placeholder="<?php echo $tr->translate("phPassword"); ?>" required="required">
									<div></div>
								</div>
							</div>
							<div class="controls">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-lock"></i></span><input id="password2" name="password2" type="password" placeholder="<?php echo $tr->translate("phPassword"); ?>" required="required">
									<div></div>
								</div>
							</div>
						</div>
						<p class="center span5">
							<button class="btn btn-primary" type="submit"><?php echo $tr->translate("btnReset"); ?></button>
						</p>
					</form>
				</div>
			</div>
			<?php } ?>
		</div>
	</div><!--/span-->
</div><!--/row-->

<?php require "../_container/container_bottom.php"; ?>
<script>
	$(document).ready(function() {
		$("#loginDiv").show();
		$("form").validate({
			rules: {
				username: {required: true},
				password: {required: true, minlength: 5},
				password2: {required: true, minlength: 5, equalTo: "#password"}
			},
			errorPlacement: function(error, element) {
				error.appendTo( $(element).next());
			}
		}); 
	});
</script>