<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/layout.php';

if (isAdminSetupRequired()) {
    header('Location: admin/setup_admin.php');
    exit;
}
redirectIfLoggedIn();

$message = isset($_GET['message']) ? trim((string)$_GET['message']) : '';
$returnUrl = safeReturnUrl($_GET['return'] ?? $_POST['return'] ?? 'admin/index.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = :username AND is_active = 1 LIMIT 1");
        $stmt->execute([':username' => $username]);
        $user = $stmt->fetch();
        $locked = $user && !empty($user['locked_until']) && strtotime($user['locked_until']) > time();

        if ($locked) {
            logAdminAction('login_failed', 'Locked account login attempt: ' . $username, $user['id'] ?? null);
            if (function_exists('writeAppLog')) writeAppLog('warning', 'login_error', 'Locked account login attempt', ['username' => $username, 'admin_id' => $user['id'] ?? null]);
            $message = '잠시 후 다시 시도하세요.';
        } elseif ($user && password_verify($password, $user['password_hash'])) {
            $update = $pdo->prepare("UPDATE admin_users SET login_fail_count = 0, locked_until = NULL, last_login_at = NOW() WHERE id = :id");
            $update->execute([':id' => $user['id']]);
            loginAdmin($user);
            logAdminAction('login_success', '관리자 로그인');
            if (function_exists('writeAppLog')) writeAppLog('info', 'audit', 'Admin login success', ['action' => 'login_success', 'admin_id' => $user['id'], 'admin_name' => $user['username'], 'result' => 'success']);
            header('Location: ' . $returnUrl);
            exit;
        } else {
            if ($user) {
                $failCount = ((int)$user['login_fail_count']) + 1;
                $lockedUntil = $failCount >= 5 ? date('Y-m-d H:i:s', time() + 600) : null;
                $update = $pdo->prepare("UPDATE admin_users SET login_fail_count = :fail_count, locked_until = :locked_until WHERE id = :id");
                $update->execute([':fail_count' => $failCount, ':locked_until' => $lockedUntil, ':id' => $user['id']]);
                logAdminAction('login_failed', 'Login failed: ' . $username, $user['id']);
                if (function_exists('writeAppLog')) writeAppLog('warning', 'login_error', 'Admin login failed', ['username' => $username, 'admin_id' => $user['id'], 'fail_count' => $failCount]);
            } else {
                logAdminAction('login_failed', 'Login failed for unknown user: ' . $username);
                if (function_exists('writeAppLog')) writeAppLog('warning', 'login_error', 'Unknown admin login failed', ['username' => $username]);
            }
            $message = '아이디 또는 비밀번호가 올바르지 않습니다.';
        }
    } catch (Exception $e) {
        $message = '로그인 처리 중 오류가 발생했습니다.';
    }
}

renderHeader('관리자 로그인', 'login');
?>
<div class="auth-page">
    <section class="auth-card">
        <div class="auth-heading">
            <i class="fa-solid fa-lock"></i>
            <h1>관리자 로그인</h1>
            <p>설정, 스캔, 백업, 메타데이터 수정 기능은 로그인 후 사용할 수 있습니다.</p>
        </div>
        <?php if ($message !== ''): ?>
            <div class="alert-box alert-danger"><div class="alert-content"><p><?php echo h($message); ?></p></div></div>
        <?php endif; ?>
        <form method="POST" class="auth-form">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="return" value="<?php echo h($returnUrl); ?>">
            <label>아이디<input type="text" name="username" required autocomplete="username"></label>
            <label>비밀번호<input type="password" name="password" required autocomplete="current-password"></label>
            <button type="submit" class="btn btn-primary auth-submit">로그인</button>
        </form>
    </section>
</div>
<?php renderFooter(); ?>
