<?php

/*
 * Login page - Users are sent here if they are not properly logged in, or their login expired.
 */
session_start();

if(isset($_GET['logout'])) {
    $_SESSION = array();
    session_unset();
    session_destroy();
    header("Location: index.php?page=home");
    die("Error, please enable browser redirects.");
}

if (isset($_SESSION['user'])) {
    header("Location: index.php?page=home");
    die("Error, please enable browser redirects.");
}

mb_internal_encoding("utf-8"); // Internal encoding set to UTF-8, should fix some charset issues.

require_once("include.php"); // Our includes.

/*
 * Get variables and sanitize their inputs
 */
$error = array();

if (isset($_POST['u']) && isset($_POST['p'])) {
    // If mail and pw is set, lets do some sanitizng.

    if (filter_input(INPUT_POST, 'u', FILTER_DEFAULT) == true) {
        $email = $_POST['u'];
    } else {
        $error[] = "Email or username incorrect.";
    }

    if (filter_input(INPUT_POST, 'p', FILTER_DEFAULT) == true) {
        $password = $_POST['p'];
    } else {
        $error[] = "Email or username incorrect.";
    }

    $db = new DBClass();
    $query = "SELECT * FROM `" . Config::$db_tableusers . "` WHERE `username` = '" . $email . "'";

    if ($db->numRows($db->query($query)) >= 1) {
        $result = $db->fetchAll($db->query($query))[0];
        if (password_verify($password, $result['password']) && $email == $result['username']) {
            // SUCCESS!
            $_SESSION['user'] = $result['id'];
            $_SESSION['username'] = $result['username'];
            $_SESSION['lvl'] = $result['level'];

            header('Location: index.php?page=news');
            die("Error, please enable browser redirects.");
        } else {
            $error[] = "Mail wrong";
        }
    } else {
        $error[] = "Wrong email or password.";
        header('Location: index.php?page=login&error=1');
    }
}


/*
 * If no information was sent to the script, or the login was incorrect - HTML below here will be shown.
 */

header('Location: ' . Config::$sys_url . '?page=login&error=1');
die("Error, please enable browser redirects.");

