<?php
include 'config.php';

if (isset($_SESSION['user_id']) || isset($_COOKIE['remember_token'])) {
    header('Location: dashboard.php');
    exit();
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitizeInput($_POST['username']);
    $password = $_POST['password'];
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        $_SESSION['full_name'] = $user['full_name'];
        
        if (isset($_POST['remember'])) {
            $token = bin2hex(random_bytes(32));
            setcookie('remember_token', $token, time() + 86400 * 30, '/');
            // Сохраняем токен в базе данных
            $pdo->prepare("UPDATE users SET remember_token = ? WHERE id = ?")
                ->execute([$token, $user['id']]);
        }
        
        header('Location: dashboard.php');
        exit();
    } else {
        $error = "❌ Неверные учетные данные!";
    }
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🌾 Агротопливо - Вход</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body class="auth-body">
    <div class="auth-container">
        <div class="auth-header">
            <div class="logo">🚜</div>
            <h1>Агротопливо</h1>
            <p>Система учёта расхода топлива</p>
        </div>
        
        <form method="POST" class="auth-form">
            <?php if($error): ?>
                <div class="alert error"><?php echo $error; ?></div>
            <?php endif; ?>
            
            <div class="form-group">
                <label>👤 Имя пользователя</label>
                <input type="text" name="username" value="<?php echo $_POST['username'] ?? ''; ?>" required>
            </div>
            
            <div class="form-group">
                <label>🔒 Пароль</label>
                <input type="password" name="password" required>
            </div>
            
            <div class="form-group checkbox">
                <label>
                    <input type="checkbox" name="remember">
                    <span class="checkmark"></span>
                    Запомнить меня
                </label>
            </div>
            
            <button type="submit" class="btn btn-primary btn-large">🚜 Войти в систему</button>
        </form>
    </div>
</body>
</html>