<?php
// index.php — halaman login
require_once 'includes/config.php';
require_once 'includes/auth.php';

// Jika sudah login, redirect
if (isLoggedIn()) {
    $dest = $_SESSION['role'] === 'admin' ? 'admin/dashboard.php' : 'kasir/dashboard.php';
    header('Location: ' . BASE_URL . $dest);
    exit;
}

$error = '';

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

    if ($username && $password) {
        $stmt = $pdo->prepare("SELECT * FROM akun WHERE username = ? AND aktif = 1 LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['nama']    = $user['nama'];
            $_SESSION['role']    = $user['role'];

            $dest = $user['role'] === 'admin' ? 'admin/dashboard.php' : 'kasir/dashboard.php';
            header('Location: ' . BASE_URL . $dest);
            exit;
        } else {
            $error = 'Username atau password salah.';
        }
    } else {
        $error = 'Harap isi semua field.';
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Login — <?= NAMA_TOKO ?></title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="<?= BASE_URL ?>css/style.css?v=<?= time() ?>">
</head>
<body>
<div class="login-page">
  <div class="login-card">
    <div class="login-logo">🛒</div>
    <h1><?= NAMA_TOKO ?></h1>
    <p>Masuk ke Sistem POS</p>

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

    <form method="POST">
      <div class="form-group">
        <label>Username</label>
        <input type="text" name="username" class="form-control" placeholder="Masukkan username..." required autofocus>
      </div>
      <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" class="form-control" placeholder="Masukkan password..." required>
      </div>
      <button type="submit" class="btn btn-primary" style="width:100%;padding:14px;font-size:15px;border-radius:12px;justify-content:center;">
        Masuk
      </button>
    </form>

    <p style="margin-top:20px;text-align:center;font-size:12px;color:var(--muted);">
      Default: admin / password123 &nbsp;|&nbsp; kasir1 / password123
    </p>
  </div>
</div>
</body>
</html>
