<?php
include 'header.php'; // include koneksi & session
$pesan_error = "";
$pesan_sukses = "";

// Jika sudah login, tendang ke dashboard
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

// Cek jika ada notif dari register
if (isset($_GET['status']) && $_GET['status'] == 'register_sukses') {
    $pesan_sukses = "Registrasi berhasil! Silakan login.";
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = mysqli_real_escape_string($koneksi, $_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        $pesan_error = "Username dan Password wajib diisi!";
    } else {
        $query = "SELECT * FROM users WHERE username = '$username'";
        $result = mysqli_query($koneksi, $query);

        if (mysqli_num_rows($result) == 1) {
            $user = mysqli_fetch_assoc($result);
            
            // Verifikasi password
            if (password_verify($password, $user['password'])) {
                // Password benar, buat session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['nama'] = $user['nama'];
                
                header("Location: index.php"); // Redirect ke dashboard
                exit;
            } else {
                $pesan_error = "Username atau Password salah.";
            }
        } else {
            $pesan_error = "Username atau Password salah.";
        }
    }
}
?>

<div class="login-container">

    <div class="login-logo">
        <img src="assets/logo.png" alt="Logo Perpustakaan">
    </div>

    <h2 class="login-title">Login</h2>




<div>




    <div class="card">
        <form action="login.php" method="POST">
            <?php if(!empty($pesan_error)) { echo "<p style='color:red;'>$pesan_error</p>"; } ?>
            <?php if(!empty($pesan_sukses)) { echo "<p style='color:green;'>$pesan_sukses</p>"; } ?>

            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;">Login</button>
        </form>
    </div>
    <p style="margin-top: 15px;">
        Belum punya akun? <a href="register.php">Daftar disini</a>
    </p>
</div>

<?php include 'footer.php'; ?>