<?php
ob_start();

$template_dir = "templates/";

if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(!empty($_POST["email"]) && !empty($_POST["password"])){
        $email = $_POST["email"];
        $pass = $_POST["password"];
        /* prepare statement */
        $stmt = $mysqli->prepare("SELECT ID, PSWD, IGN, ISADMIN FROM Users where EMAIL = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        /* bind variables to prepared statement */
        $stmt->bind_result($idcko, $hash, $ign, $isadmin);
        
        $found = false;
        /* fetch values */
        while ($stmt->fetch()) {
            if (password_verify($pass, $hash)){
                $_SESSION["ID"] = $idcko;
                $_SESSION["email"] = $email;
                $_SESSION["ign"] = $ign;
                $_SESSION["isadmin"] = $isadmin;
                $found = true; 
                break;
            }
            else{
                $_SESSION["ID"] = 0;
                $_SESSION["email"] = "";
                $_SESSION["ign"] = "";
                $_SESSION["isadmin"] = 0;
                $found = false;
            }
            break;
        }
        if($found){
            echo "Login successful";
        }
        else{
            echo "Login failed";
        }
    }
}
if ($_SESSION["ID"] > 0){
    $account_template = file_get_contents($template_dir . "account.html");
    echo $account_template;
}
else{
    $login_template = file_get_contents($template_dir . "login.html");
    echo $login_template;
}

return ob_get_clean();

?>