<?php
session_start();

// Jika pengguna sudah login, alihkan ke halaman utama
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: /");
    exit;
}

// Memuat konfigurasi database
require_once "../setting/database.php";

// Inisialisasi variabel
$username = $password = "";
$username_err = $password_err = $login_err = "";

// Memproses data form saat form dikirim
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Validasi username
    if(empty(trim($_POST["username"]))){
        $username_err = "Silakan masukkan username.";
    } else{
        $username = trim($_POST["username"]);
    }

    // Validasi password
    if(empty(trim($_POST["password"]))){
        $password_err = "Silakan masukkan password Anda.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Jika tidak ada error validasi
    if(empty($username_err) && empty($password_err)){
        $sql = "SELECT id, username, password, role FROM users WHERE username = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            $param_username = $username;
            
            if(mysqli_stmt_execute($stmt)){
                mysqli_stmt_store_result($stmt);
                
                if(mysqli_stmt_num_rows($stmt) == 1){                    
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password, $role);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password benar, mulai sesi baru
                            session_start();
                            
                            // Simpan data dalam variabel sesi
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;
                            $_SESSION["role"] = $role;                            
                            
                            // Alihkan ke halaman utama
                            header("location: /");
                        } else{
                            // Tampilkan pesan error jika password tidak valid
                            $login_err = "Username atau password salah.";
                        }
                    }
                } else{
                    // Tampilkan pesan error jika username tidak ditemukan
                    $login_err = "Username atau password salah.";
                }
            } else{
                echo "Oops! Terjadi kesalahan. Silakan coba lagi nanti.";
            }

            mysqli_stmt_close($stmt);
        }
    }
    
    mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <style>
        /* CSS untuk memusatkan form */
        body, html {
            height: 100%;
        }
        .container-login {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100%;
        }
        .card {
            width: 100%;
            max-width: 400px;
        }
    </style>
</head>
<body class="bg-light">

    <div class="container-login">
        <div class="card shadow-sm">
            <div class="card-body p-4 p-md-5">
                <h2 class="card-title text-center mb-4">Login</h2>
                
                <?php 
                if(!empty($login_err)){
                    echo '<div class="alert alert-danger">' . $login_err . '</div>';
                }        
                ?>

                <form action="login" method="post" novalidate>
                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" name="username" id="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo htmlspecialchars($username); ?>">
                        <div class="invalid-feedback">
                            <?php echo $username_err; ?>
                        </div>
                    </div>    
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" name="password" id="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                        <div class="invalid-feedback">
                            <?php echo $password_err; ?>
                        </div>
                    </div>
                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-primary">Login</button>
                    </div>
                    <hr class="my-4">
                    <p class="text-center">Belum punya akun? <a href="daftar">Daftar sekarang</a>.</p>
                    <p class="text-center"><a href="lupa-password" class="text-muted"><small>Lupa password?</small></a></p>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>
</html>
