<?php
/**
 * Страница входа
 */

session_start();

require_once __DIR__ . '/classes/Auth.php';

$auth = new Auth();

// If no users, redirect to setup
if (!$auth->hasUsers()) {
    header('Location: setup.php');
    exit;
}

// If already logged in, redirect to main page
if ($auth->isAuthenticated()) {
    header('Location: index.php');
    exit;
}

$error = '';
$message = '';

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $ip = Auth::getClientIP();

    if (empty($username) || empty($password)) {
        $error = 'Введите имя пользователя и пароль';
    } else {
        $result = $auth->login($username, $password, $ip);

        if ($result['success']) {
            $auth->startSession($result['username'], $result['token']);
            header('Location: index.php');
            exit;
        } else {
            $error = $result['message'];
        }
    }
}

// CSRF token
$csrfToken = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrfToken;
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Вход - VH Posting System</title>
    <link rel="icon" type="image/png" href="image.png">
    <link rel="stylesheet" href="css/style.css?v=<?= filemtime(__DIR__ . '/css/style.css') ?>">
    <script>
        // Apply saved theme immediately
        (function() {
            const theme = localStorage.getItem('theme') || 'light';
            if (theme === 'dark') {
                document.documentElement.setAttribute('data-theme', 'dark');
            }
        })();
    </script>
</head>
<body class="login-page">
    <div class="login-container">
        <div class="login-box">
            <div class="login-logo">
                <img src="image.png" alt="VH Logo" class="login-logo-img" style="width:100px;height:100px;max-width:100px;max-height:100px;">
            </div>
            <h1>VH Posting System</h1>
            <h2>Вход в систему</h2>

            <?php if ($error): ?>
                <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="POST" action="login.php">
                <input type="hidden" name="csrf_token" value="<?= $csrfToken ?>">

                <div class="form-group">
                    <label for="username">Имя пользователя:</label>
                    <input type="text" id="username" name="username" required autofocus
                           value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                </div>

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

                <button type="submit" class="btn btn-primary btn-large btn-block">Войти</button>
            </form>
        </div>
    </div>
</body>
</html>
