<?php
session_start();
include 'db.php';

// Pastikan koneksi berhasil
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user  = trim($_POST['user']);
    $sandi = trim($_POST['sandi']);

    // Siapkan query untuk mencari user
    $stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
    $stmt->bind_param("s", $user);
    $stmt->execute();
    $stmt->bind_result($username, $password);
    $stmt->fetch();
    $stmt->close();

    // Verifikasi password
    if ($username && password_verify($sandi, $password)) {
        $_SESSION['username'] = $username;
        header("Location: dashboard.php");
        exit;
    } else {
        $error = "❌ Username atau password salah. Ulangi!";
    }
}
?>

<html>
<head>
<title>Login</title>
<style>
body {
    background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
    font-family: Arial, sans-serif;
}
.login-box {
    margin: 150px auto;
    width: 320px;
    padding: 25px;
    background: white;
    border-radius: 15px;
    box-shadow: 0 0 10px rgba(0,0,0,0.2);
    text-align: center;
}
input[type=text], input[type=password] {
    width: 90%;
    padding: 8px;
    margin: 8px 0;
    border: 1px solid #ccc;
    border-radius: 8px;
}
input[type=submit] {
    width: 95%;
    padding: 10px;
    background-color: #4CAF50;
    border: none;
    border-radius: 8px;
    color: white;
    font-size: 16px;
    cursor: pointer;
}
input[type=submit]:hover {
    background-color: #45a049;
}
.error {
    color: red;
    font-weight: bold;
}
</style>
</head>

<body>
<div class="login-box">
<h2>🔐 Login</h2>
<form method="post">
    <input type="text" name="user" placeholder="Masukkan username" required><br>
    <input type="password" name="sandi" placeholder="Masukkan password" required><br><br>
    <input type="submit" value="Login">
</form>

<?php if (!empty($error)) echo "<p class='error'>$error</p>"; ?>
</div>
</body>
</html>
