<?
support_login_listener();


if(isset($_SESSION['login_id']) && $_SESSION['login_id'] != 0){
	// if ($_SESSION['login_id'] == "827") {
	// 	$_SESSION['login_id'] = "351";
	// }
	check_if_read_collection($_GET['collection_id']);
	update_contact_last_interaction($_SESSION['login_id']);
}else{
	if (($_GET["action"] == 'intranet_forgot_password') || ($_GET["action"] == 'intranet_password_remind') || ($_GET["action"] == 'intranet_password_code') || ($_GET["action"] == 'intranet_set_password') || ($_GET["action"] == 'intranet_set_password_finished')){
		die(require_once("intranet_password.php"));
	}else if (($_GET["action"] == 'intranet_register')){
		die(require_once("intranet_register.php"));
	}else{
		die(require_once("intranet_login.php"));
	}
}

function support_login_listener() {
	$_SESSION["login_error"] = "";
	$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
	
	switch ($_GET["action"]) {
		case "intranet_logout":
			$_SESSION['login_id'] = 0;
			header('location:/');
			break;
		case "intranet_login":
			if(($_POST["input_login"]<>'') && ($_POST["input_password"]<>'')) {
				$login = $_POST["input_login"];
				$password_hash = md5($_POST["input_password"]);

				$query = "SELECT * from main_contact WHERE shortcut = '$login'";
				$result = @mysqli_query($GLOBALS['mysql_con'], $query);
				if (@mysqli_num_rows($result) > 0) {
					while ($main_contact = @mysqli_fetch_array($result)) {
						if($main_contact['password'] == $password_hash){
							if($main_contact['active'] == 0){
								$_SESSION["login_error"] = "Dieser Account wurde noch nicht freigeschalten.";
							}else{
								$_SESSION['login_id'] = $main_contact['id'];
								header('location:/');
							}
						}else{
							$_SESSION["login_error"] = "Das eingegebene Passwort ist nicht korrekt.";
						}
					}
				}else{
					$_SESSION["login_error"] = "Die eingegebene E-Mail ist nicht vorhanden.";
				}
			}
			break;
	case "change_mandant":
    $current_mandant_id = (int)$_GET['id'];
    if ($current_mandant_id <= 0) {
        $current_mandant_id = (int)$GLOBALS['main_contact']['master_mandant_id'];
    }

    $query = "UPDATE main_contact 
              SET current_mandant_id = {$current_mandant_id} 
              WHERE id = " . (int)$GLOBALS['main_contact']['id'];
    mysqli_query($GLOBALS['mysql_con'], $query);

    header('location:' . $_SERVER['HTTP_REFERER']);
    exit;
		case "intranet_register_finish":
			$password_hash = md5($_POST["input_password"]);
			$email = $_POST["input_email"];
			$birthday = new DateTime($_POST["input_birthday"]);
			$query = "INSERT INTO main_contact SET 
				name = '".$_POST['input_name']."',
				address = '".$_POST['input_address']."',
				post_code = '".$_POST['input_post_code']."',
				city = '".$_POST['input_city']."',
				birthday = '".$birthday->format('Y-m-d')."',
				phone_no = '".$_POST['input_phone_no']."',
				email = '".$email."',
				password = '".$password_hash."',
				image = '',
				active = '0'";
			@mysqli_query($GLOBALS['mysql_con'], $query);
			return true;
		case "intranet_password_code":
			$translation  = \DynCom\mysyde\common\classes\Registry::get("translation");
         	if($_POST["input_login"]<>'') {
				$email = $_POST["input_login"];
				$query = "SELECT * FROM main_contact WHERE email = '".$email."' LIMIT 1";
				$result = @mysqli_query($GLOBALS['mysql_con'], $query);
				
				if(@mysqli_num_rows($result) < 1){
					$_SESSION['login_error'] = 'Falsche E-Mail';
				}else{
					unset($_SESSION['login_error']);
					$user = @mysqli_fetch_assoc($result);
					$randomString = time().$user['id'].rand(9999,999999);
					$queryUpd = "UPDATE main_contact SET password_recovery_code = '" . $randomString . "' WHERE id = '" . $user["id"] . "' LIMIT 1";

					$message = '<p> Hallo '.$user['name'].',<br>Unten ist Ihr Passwort-Wiederherstellungscode<br></p>';
					$message .= "<p><strong>".$randomString."</strong></p>";
					$contactform_header["subject"] = "E-Mail zur Passwortwiederherstellung";
					$contactform_header["sender_email"] = 'support@'.$_SERVER['HTTP_HOST'];
					$contactform_header["recipient_email"] = $user['email'];
					$contactform_header["sender_name"] = "Support Team";
					$contactform_header["recipient_name"] = $user['name'];
				
					if (mail_create( $contactform_header["subject"],
						$message,
						$contactform_header["sender_email"],
						$contactform_header["recipient_email"],
						$contactform_header["sender_name"],
						$contactform_header["recipient_name"],
						TRUE,
						"")) {
						mail_send();
						@mysqli_query($GLOBALS['mysql_con'], $queryUpd);
						$_SESSION['user_email'] = $email;
					}else{
						$_SESSION['login_error'] = "Unbekannter Fehler aufgetreten, versuchen Sie es erneut";
					}
				}
			}
			break;
		case "intranet_set_password":
			$email = $_SESSION['user_email'];
			$code = $_POST['password_recovery_code'];
			$query = "SELECT * FROM main_contact WHERE email = '".$email."' AND password_recovery_code = '".$code."' LIMIT 1";
			$result = @mysqli_query($GLOBALS['mysql_con'], $query);
			if(@mysqli_num_rows($result) < 1){
				$_GET['action'] = 'intranet_password_code';
                header('Location: /?action='.$_GET['action'] );
				$_SESSION['login_error'] = 'Falsche E-Mail oder Code';   
			}else{
				unset($_SESSION['login_error']);
				$user = @mysqli_fetch_assoc($result);
				$queryUpd = "UPDATE main_contact SET password_recovery_code = '' WHERE id = '" . $user["id"] . "' LIMIT 1";
				@mysqli_query($GLOBALS['mysql_con'], $queryUpd);
                $_SESSION['code_set'] = 1;
			}
			break;
		case "intranet_set_password_finished":
			if($_POST['input_password'] <> '' && $_POST['input_password_2'] <> ''){
				$email = $_SESSION['user_email'];
				$query = "SELECT * FROM main_contact WHERE email = '".$email."' LIMIT 1";

				if ($_POST["input_password"] <> $_POST["input_password_2"]) {
					$_SESSION['forget_error'] = $translation->get("user_error2");
				}else if (strlen($_POST["input_password"]) < 6) {
					$_SESSION['forget_error'] = $translation->get("user_error3");
				}else{
					unset($_SESSION['forget_error']);
					$result = @mysqli_query($GLOBALS['mysql_con'], $query);
					$user = @mysqli_fetch_assoc($result);

					$password = md5($_POST["input_password"]);
					$queryUpd = "UPDATE main_contact SET password = '".$password."' WHERE id = '" . $user["id"] . "' LIMIT 1";
					if(@mysqli_query($GLOBALS['mysql_con'], $queryUpd)){
						$_SESSION['success_status'] = $translation->get("user_msg_success2");
						unset($_SESSION['user_email']);
						unset($_SESSION['code_set']);
						header('Location: /?action=');
					}else{
						$_SESSION['forget_error'] = 'Das Passwort kann nicht aktualisiert werden. Versuchen Sie es nochmal.';
					}    
				} 
			}
        default:
            break;
	}
}

function update_contact_password($main_contact_id, $password){
	$password_hash = md5($password);
	$query = "UPDATE main_contact SET
	password_recovery_code = '" . $password_hash . "'
	WHERE id = '" . $main_contact_id . "' LIMIT 1";
  	@mysqli_query($GLOBALS['mysql_con'],$query);
}

function update_contact_last_interaction($main_contact_id){
	$last_interaction = new DateTime();
	$query = "UPDATE main_contact SET last_interaction = '" . $last_interaction->format('Y-m-d H:i:s') . "' WHERE id = '" . $main_contact_id . "' LIMIT 1";
  	@mysqli_query($GLOBALS['mysql_con'],$query);
}

function check_if_read_collection($collection_id){
	$current_date = new DateTime();
    $query = "SELECT * FROM main_collection_read WHERE main_collection_id = '".$collection_id."' AND main_contact_id = '".$GLOBALS['main_contact']['id']."'";
    $result = mysqli_query($GLOBALS["mysql_con"], $query);
    if (@mysqli_num_rows($result) == 0) {
        $query = "INSERT INTO main_collection_read (main_collection_id, main_contact_id, read_on) VALUES (
            '".$collection_id."',
            '".$GLOBALS['main_contact']['id']."',
            '".$current_date->format('Y-m-d H:i:s')."'
        )";
        $result = mysqli_query($GLOBALS["mysql_con"], $query);
    }
}

function get_permission_state($permission_code, $mandant_id, $contact_id)
{
	$return = 0;

	$stmt_permission = mysqli_prepare($GLOBALS["mysql_con"], "SELECT * FROM main_permission WHERE code = ?");
	mysqli_stmt_bind_param($stmt_permission, "s", $permission_code);
	mysqli_stmt_execute($stmt_permission);
	$result_permission = mysqli_stmt_get_result($stmt_permission);
	$permission = mysqli_fetch_array($result_permission);
	mysqli_stmt_close($stmt_permission);
	if ($permission['default_active'] == 1) {
		$return = 1;
	}
	$stmt_contact = mysqli_prepare($GLOBALS["mysql_con"], "SELECT * FROM main_contact_permission WHERE main_contact_id = ? AND main_mandant_id = ? AND main_permission_id = ?");
	mysqli_stmt_bind_param($stmt_contact, "iii", $contact_id, $mandant_id, $permission['id']);
	mysqli_stmt_execute($stmt_contact);
	$result_contact = mysqli_stmt_get_result($stmt_contact);
	$contact = mysqli_fetch_array($result_contact);
	if (mysqli_num_rows($result_contact) == 1) {
		$return = $contact['active'];
	}
	mysqli_stmt_close($stmt_contact);
	return $return;
}
