<?php
session_start();
$conn = new mysqli("localhost","root","","breakout_db");
if($conn->connect_error){ die("DB Error"); }

if(isset($_POST['register'])){
    $u = $_POST['user'];
    $p = password_hash($_POST['pass'], PASSWORD_DEFAULT);
    $u_safe = $conn->real_escape_string($u);
    $conn->query("INSERT INTO users(username,password,highscore_easy, highscore_medium, highscore_hard) VALUES('$u_safe','$p',0,0,0)");
    if($conn->affected_rows > 0) {
        $_SESSION['user'] = $u;
        header("Location: index.php");
        exit;
    }
}

if(isset($_POST['login'])){
    $u = $_POST['user'];
    $p = $_POST['pass'];
    $u_safe = $conn->real_escape_string($u);
    $res = $conn->query("SELECT * FROM users WHERE username='$u_safe'");
    if($row = $res->fetch_assoc()){
        if(password_verify($p, $row['password'])){
            $_SESSION['user'] = $u;
            header("Location: index.php");
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login & Register</title>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<link rel="stylesheet" href="style.css">

</head>
<body class="login-body">

<div class="login-box">

    <h2><i class="fas fa-user"></i> Login</h2>
    <form method="POST">
        <input name="user" placeholder="Username" required>
        <input name="pass" type="password" placeholder="Password" required>
        <button name="login">Login</button>
    </form>

    <hr>

    <h2><i class="fas fa-user-plus"></i> Register</h2>
    <form method="POST">
        <input name="user" placeholder="Username" required>
        <input name="pass" type="password" placeholder="Password" required>
        <button name="register">Register</button>
    </form>

    
    <a href="index.php" class="back-button" style="margin-top:20px; display:inline-block;">
    <i class="fas fa-arrow-left"></i> Back
</a>

</div>

</body>
</html>