<?php
session_start();
require_once 'db/config.php';

$error = '';

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

    if (empty($email) || empty($password)) {
        $error = 'Proszę podać email i hasło.';
    } else {
        try {
            $pdo = db();
            $stmt = $pdo->prepare("SELECT * FROM people WHERE email = ? AND is_user = TRUE AND active = TRUE");
            $stmt->execute([$email]);
            $person = $stmt->fetch();

            if ($person && password_verify($password, $person['password'])) {
                $_SESSION['user_id'] = $person['id'];
                $_SESSION['user_email'] = $person['email'];
                $_SESSION['user_role'] = $person['role'];
                $_SESSION['user_name'] = $person['first_name'] . ' ' . $person['last_name'];
                header('Location: index.php');
                exit;
            } else {
                $error = 'Nieprawidłowe dane logowania. Spróbuj ponownie.';
            }
        } catch (PDOException $e) {
            $error = 'Błąd bazy danych: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Logowanie</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: #f8f9fa;
        }
        .login-card {
            width: 100%;
            max-width: 400px;
        }
    </style>
</head>
<body>
    <div class="card login-card">
        <div class="card-body">
            <h3 class="card-title text-center mb-4">Logowanie do systemu</h3>
            <?php if ($error): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>
            <form method="POST" action="login.php">
                <div class="mb-3">
                    <label for="email" class="form-label">Adres email</label>
                    <input type="email" class="form-control" id="email" name="email" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Hasło</label>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>
                <div class="d-grid">
                    <button type="submit" class="btn btn-primary">Zaloguj się</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
