<?php
require_once 'config.php';

if(isLoggedIn()) {
    header("Location: index.php");
    exit;
}

$error = '';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login = trim($_POST['login'] ?? '');
    $password = $_POST['password'] ?? '';
    
    $stmt = $pdo->prepare("SELECT id, username, full_name, password_hash FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$login, $login]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['full_name'] = $user['full_name'];
        header("Location: index.php");
        exit;
    } else {
        $error = "Неверный логин или пароль";
    }
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Вход - СтройМастер</title>
    <meta name="description" content="Войдите в личный кабинет для отправки заявки">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Arial, sans-serif; background: linear-gradient(135deg, #1e3a5f 0%, #2d5a8b 100%); min-height: 100vh; display: flex; justify-content: center; align-items: center; }
        .form-box { background: #fff; padding: 40px; border-radius: 16px; width: 400px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); }
        h1 { margin-bottom: 25px; text-align: center; color: #0f172a; }
        input { width: 100%; padding: 12px; margin: 8px 0 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 16px; }
        button { width: 100%; padding: 12px; background: #1e3a5f; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; }
        button:hover { background: #2d5a8b; }
        .error { color: #e74c3c; margin: 10px 0; padding: 10px; background: #fdecea; border-radius: 8px; }
        .link { text-align: center; margin-top: 20px; }
        a { color: #1e3a5f; text-decoration: none; }
    </style>
</head>
<body>
<div class="form-box">
    <h1>🏗️ Вход</h1>
    <?php if($error): ?><div class="error"><?= h($error) ?></div><?php endif; ?>
    <form method="POST">
        <input type="text" name="login" placeholder="👤 Имя пользователя или Email" required>
        <input type="password" name="password" placeholder="🔒 Пароль" required>
        <button type="submit">Войти</button>
    </form>
    <div class="link">Нет аккаунта? <a href="register.php">Регистрация</a></div>
</div>
</body>
</html>