<?php
session_start();

include 'db.php';

// --- Koneksi ke database ---
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Koneksi gagal: " . htmlspecialchars($conn->connect_error));
}

$error = "";

// --- Jika sudah ada session, langsung ke dashboard ---
if (isset($_SESSION['username'])) {
    header("Location: dashboard.php");
    exit;
}

// --- Jika ada cookie login aktif ---
if (!isset($_SESSION['username']) && isset($_COOKIE['remember_token'])) {
    $token = $_COOKIE['remember_token'];

    $stmt = $conn->prepare("SELECT username FROM users WHERE remember_token = ? LIMIT 1");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $_SESSION['username'] = $row['username'];
        header("Location: dashboard.php");
        exit;
    }
    $stmt->close();
}

// --- Jika form login disubmit ---
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']); // cek apakah user pilih "ingat saya"

    if ($username === '' || $password === '') {
        $error = "Semua kolom wajib diisi!";
    } else {
        $stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ? LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) {
            if (password_verify($password, $row['password'])) {
                $_SESSION['username'] = $username;

                // --- Jika user pilih "ingat saya" ---
                if ($remember) {
                    $token = bin2hex(random_bytes(16)); // buat token acak aman
                    $update = $conn->prepare("UPDATE users SET remember_token = ? WHERE username = ?");
                    $update->bind_param("ss", $token, $username);
                    $update->execute();
                    $update->close();

                    // Simpan cookie 7 hari
                    setcookie('remember_token', $token, time() + (7 * 24 * 60 * 60), "/", "", false, true);
                }

                header("Location: dashboard.php");
                exit;
            } else {
                $error = "Password salah!";
            }
        } else {
            $error = "Email tidak ditemukan!";
        }

        $stmt->close();
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Login User</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
  <div class="row justify-content-center">
    <div class="col-md-4">
      <div class="card shadow-lg border-0 rounded-4">
        <div class="card-body p-4">
          <h3 class="text-center mb-4">Login</h3>

          <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success text-center">
              Jika belum bisa login, coba ulangi sampai format email benar.
            </div>
          <?php endif; ?>

          <?php if (!empty($error)): ?>
            <div class="alert alert-danger text-center"><?= htmlspecialchars($error) ?></div>
          <?php endif; ?>

          <form method="POST" onsubmit="this.querySelector('button[type=submit]').disabled = true;">
            <div class="mb-3">
              <label class="form-label">Email</label>
              <input type="email" name="username" class="form-control" required>
            </div>

            <div class="mb-3">
              <label class="form-label">Password</label>
              <input type="password" name="password" class="form-control" required>
            </div>

            <div class="form-check mb-3">
              <input class="form-check-input" type="checkbox" name="remember" id="remember">
              <label class="form-check-label" for="remember">Ingat saya</label>
            </div>

            <button type="submit" class="btn btn-primary w-100">Login</button>
          </form>

          <p class="text-center mt-3">
            Belum punya akun? <a href="register.php">Daftar di sini</a>
          </p>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>
