<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$db   = "klinik";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

$error = ""; 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $hasil = $stmt->get_result();

    if ($hasil->num_rows > 0) {
        $_SESSION['username'] = $username;
        header("Location: home.php");
        exit();
    } else {
        $error = "Username atau Password salah!";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Login</title>
  <link rel="stylesheet" href="style.css" />
  <link href='https://cdn.boxicons.com/fonts/basic/boxicons.min.css' rel='stylesheet'>
  <style>
    .error-message {
        color: red;
        text-align: center;
        margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <span class="icon-close"><i class='bx bx-x'></i></span>
    <form method="POST" action="">
      <h1>LOGIN</h1>

      <?php if (!empty($error)): ?>
        <div class="error-message"><?= $error ?></div>
      <?php endif; ?>

      <div class="input-box">
        <input type="text" name="username" placeholder="Username" required />
        <i class='bx bx-user'></i>
      </div>
      <div class="input-box">
        <input type="password" id="password" name="password" placeholder="Password" required />
        <i class='bx bx-lock'></i>
      </div>
      <div class="remember-forgot">
        <label>
          <input type="checkbox" id="showPassword" /> Tampilkan Password
        </label>
      </div>
      <button type="submit" class="btn">Login</button>
      <div class="register-link">
        <p>Ngurit Base Camp</p>
      </div>
    </form>
  </div>

  <script>
    document.querySelector(".icon-close").addEventListener("click", function() {
      window.location.href = "about:blank";
    });

    document.getElementById("showPassword").addEventListener("change", function() {
      const passwordField = document.getElementById("password");
      passwordField.type = this.checked ? "text" : "password";
    });
  </script>
</body>
</html>
