<?php
require_once __DIR__ . '/inc/auth.php';
auth_session_start();

if (!empty($_SESSION['user_id'])) {
    header('Location: /service/dashboard.php');
    exit;
}

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

    if ($login === '' || $password === '') {
        $error = 'Заполните все поля.';
    } else {
        $result = auth_login($login, $password);
        if ($result['success']) {
            $redirect = $_GET['redirect'] ?? '/service/dashboard.php';
            header('Location: ' . $redirect);
            exit;
        }
        $error = $result['error'];
    }
}
?><!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Вход — AegisOne Engineering</title>
<link rel="stylesheet" href="/service-style.php">
<meta name="robots" content="noindex, nofollow">
</head>
<body class="login-page">
<div class="login-box">

    <div class="login-brand">
        <img src="/logo.php" alt="AegisOne" class="login-brand__img">
        <div class="login-brand__title">AegisOne Engineering</div>
        <div class="login-brand__subtitle">Service Portal</div>
    </div>

    <div class="login-divider"></div>

    <h1>Вход в сервисный портал</h1>

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

    <form method="post">
        <div class="form-group">
            <label for="login">Логин</label>
            <input type="text" id="login" name="login" placeholder="Введите логин" required autocomplete="username" autofocus>
        </div>
        <div class="form-group">
            <label for="password">Пароль</label>
            <input type="password" id="password" name="password" placeholder="Введите пароль" required autocomplete="current-password">
        </div>
        <button type="submit" class="btn btn-primary btn-block">Войти</button>
    </form>

    <p class="login-box__footnote">
        * Сервисный портал для сотрудников AegisOne Engineering
    </p>
</div>
</body>
</html>
