<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';

// Redirect jika sudah login
if (isLoggedIn()) redirect(BASE_URL . '/modules/dashboard/index.php');

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $error = 'Token tidak valid. Silakan coba lagi.';
    } else {
        $username = sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($username) || empty($password)) {
            $error = 'Username dan password wajib diisi.';
        } else {
            $user = Database::fetchOne(
                "SELECT * FROM users WHERE (username=? OR email=?) AND aktif=1",
                [$username, $username]
            );

            if ($user && password_verify($password, $user['password'])) {
                // Set session
                session_regenerate_id(true);
                $_SESSION['user_id']    = $user['id'];
                $_SESSION['nama']       = $user['nama'];
                $_SESSION['username']   = $user['username'];
                $_SESSION['role']       = $user['role'];
                $_SESSION['sekolah_id'] = $user['sekolah_id'];

                // Update last login
                Database::execute("UPDATE users SET last_login=NOW() WHERE id=?", [$user['id']]);
                auditLog('LOGIN', 'users', $user['id'], 'Login berhasil');

                redirect(BASE_URL . '/modules/dashboard/index.php');
            } else {
                $error = 'Username atau password salah.';
                // Throttle (sederhana)
                sleep(1);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login — <?= APP_NAME ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Playfair+Display:wght@600&display=swap" rel="stylesheet">
<link href="<?= BASE_URL ?>/assets/css/app.css" rel="stylesheet">
</head>
<body class="login-page">
  <div class="login-card">
    <div class="login-card-header">
      <div class="login-logo">
        <i class="bi bi-mortarboard-fill"></i>
      </div>
      <h4 class="text-white fw-700 mb-1" style="font-family:var(--font-serif)"><?= APP_NAME ?></h4>
      <p class="text-white mb-0" style="opacity:.75;font-size:.8rem"><?= APP_INSTANSI ?></p>
    </div>

    <div class="login-card-body">
      <p class="text-center text-muted mb-4" style="font-size:.85rem">
        Masuk untuk mengakses sistem informasi pendampingan sekolah
      </p>

      <?php if($error): ?>
      <div class="alert alert-danger alert-dismissible fade show border-0 py-2" style="font-size:.85rem">
        <i class="bi bi-exclamation-triangle-fill me-2"></i><?= e($error) ?>
        <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>

      <form method="POST" action="" autocomplete="on" novalidate>
        <?= csrf_field() ?>

        <div class="mb-3">
          <label class="form-label">Username / Email</label>
          <div class="input-group">
            <span class="input-group-text bg-light border-end-0">
              <i class="bi bi-person text-muted"></i>
            </span>
            <input type="text" name="username" class="form-control border-start-0 ps-0"
                   placeholder="Username atau email"
                   value="<?= e($_POST['username'] ?? '') ?>"
                   required autocomplete="username">
          </div>
        </div>

        <div class="mb-4">
          <label class="form-label">Password</label>
          <div class="input-group">
            <span class="input-group-text bg-light border-end-0">
              <i class="bi bi-lock text-muted"></i>
            </span>
            <input type="password" name="password" id="password"
                   class="form-control border-start-0 ps-0 border-end-0"
                   placeholder="Kata sandi" required autocomplete="current-password">
            <button type="button" class="input-group-text bg-light" id="togglePwd">
              <i class="bi bi-eye text-muted" id="eyeIcon"></i>
            </button>
          </div>
        </div>

        <button type="submit" class="btn btn-primary w-100 py-2 fw-700">
          <i class="bi bi-box-arrow-in-right me-2"></i>Masuk
        </button>
      </form>

      <div class="text-center mt-4 text-muted" style="font-size:.75rem">
        <i class="bi bi-shield-lock me-1"></i>
        Sistem terlindungi. Hanya pengguna yang berwenang.
      </div>
    </div>
  </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('togglePwd')?.addEventListener('click', function() {
  const pwd = document.getElementById('password');
  const icon = document.getElementById('eyeIcon');
  if (pwd.type === 'password') {
    pwd.type = 'text';
    icon.className = 'bi bi-eye-slash text-muted';
  } else {
    pwd.type = 'password';
    icon.className = 'bi bi-eye text-muted';
  }
});
</script>
</body>
</html>
