<?php 
session_start();
include "config/db.php";

if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    if ($username === "" || $password === "") {
        $_SESSION['flash'] = "Data harus lengkap!";
    } else {

        $sql = "SELECT * FROM users WHERE username = ?";
        $stmt = $db->prepare($sql); // agar aman dari sql injection
        $stmt->bind_param("s", $username); // agar rapi tidak muncul di bagian atas query
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {

            $user = $result->fetch_assoc();

            if (password_verify($password, $user['password'])) {
                $_SESSION['loggedin'] = true;
                $_SESSION['username'] = $user['username'];
                $_SESSION['id'] = $user['id'];
                $_SESSION['flash'] = "Wellcome to Dungeon, player $username";
                header("Location: onboard.php");
                exit();

            } else {
                $_SESSION['flash'] = "Password salah!";
            }

        } else {
            $_SESSION['flash'] = "Username tidak ditemukan!";
        }
    }
    
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>codebeater</title>
    <link rel="icon" type="image/png" href="/assets/Design/mini-icon-cave.png">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/global.css">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div class="container-login">
        <?php
    include "notif.php";

    if (isset($_SESSION['flash'])) {
        echo "<script>showNotif(" . json_encode($_SESSION['flash']) . ");</script>";
        unset($_SESSION['flash']);
    }
    ?>

        <h1 data-aos="zoom-out" data-aos-duration="1000">codebeater</h1>
        <form class="login-form" action ="index.php" method="POST">
            <h2 data-aos="fade-up" data-aos-duration="1000">Login to your account</h2>
            <input type="text" name="username" id="username" placeholder="input your username"  data-aos="fade-up" data-aos-duration="2000"><br>
            <input type="password" name="password" id="password" placeholder="input your password" data-aos="fade-up" data-aos-duration="2000"><br>
            <button type="submit" name="login"  data-aos="fade-up" data-aos-duration="3000">LOGIN</button>
            <p data-aos="fade-up" data-aos-duration="3000"><a href="register.php">don't have account yet?<span> register now!</span></a></p>
        </form>
        <div id="notif" class="notif"></div>
    </div>
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
        AOS.init();
    </script>
</body>
</html>