<?php
session_start();
include './includes/db_config.php';

if (isset($_SESSION['user_id'])) {
    header("Location: ./index.php");
    exit;
}

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

    $sql = "SELECT id, username, password, role, is_verified FROM users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password']) && (int)$user['is_verified'] === 1) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            header("Location: ./index.php");
            exit;
        } else {
            $error = "Невірний пароль або акаунт не підтверджений.";
        }
    } else {
        $error = "Користувач не знайдений.";
    }
    $stmt->close();
}

$conn->close();

/* ===== підготовка header.php ===== */
$siteName  = 'Розклад занять';
$pageTitle = 'Увійти';
$pageCss   = [
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    '/css/auth.css?v=3'
];

include './includes/header.php';
?>

<main class="page">
  <div class="kp-container">
    <div class="auth-wrap">
      <h1 class="auth-title">Увійти</h1>

      <div class="auth-card">
        <?php if (isset($error)): ?>
          <div class="alert alert-danger" role="alert"><?= htmlspecialchars((string)$error, ENT_QUOTES, 'UTF-8'); ?></div>
        <?php endif; ?>

        <form method="POST" class="auth-form" autocomplete="on">
          <div class="mb-3">
            <label for="username" class="form-label">Ім'я користувача:</label>
            <input type="text" class="form-control" id="username" name="username" required autocomplete="username">
          </div>

          <div class="mb-3">
            <label for="password" class="form-label">Пароль:</label>
            <input type="password" class="form-control" id="password" name="password" required autocomplete="current-password">
          </div>

          <button type="submit" class="btn btn-primary w-100">Увійти</button>

          <div class="auth-links">
            <a href="/register.php">Немає акаунта? Зареєструватися</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</main>

<?php include './includes/footer.php'; ?>

</body>
</html>
