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

requirePermission('admin_manage');

$pdo = getDBConnection();
$message = '';
$status = 'success';
$roles = adminRoleLabels();

function activeSuperAdminCount() {
    $stmt = getDBConnection()->prepare("SELECT COUNT(*) FROM admin_users WHERE is_active = 1 AND role IN ('admin','super_admin')");
    $stmt->execute();
    return (int)$stmt->fetchColumn();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    try {
        $action = (string)($_POST['action'] ?? 'update_role');
        $userId = max(0, (int)($_POST['user_id'] ?? 0));
        if ($userId <= 0) {
            throw new RuntimeException('관리자 계정이 올바르지 않습니다.');
        }

        $stmt = $pdo->prepare("SELECT id, username, role, is_active FROM admin_users WHERE id = :id");
        $stmt->execute([':id' => $userId]);
        $target = $stmt->fetch();
        if (!$target) {
            throw new RuntimeException('관리자 계정을 찾을 수 없습니다.');
        }

        if ($action === 'change_password') {
            $password = (string)($_POST['password'] ?? '');
            $passwordConfirm = (string)($_POST['password_confirm'] ?? '');

            if (strlen($password) < 8) {
                throw new RuntimeException('비밀번호는 8자 이상으로 입력하세요.');
            }
            if (!hash_equals($password, $passwordConfirm)) {
                throw new RuntimeException('비밀번호 확인이 일치하지 않습니다.');
            }

            $update = $pdo->prepare("
                UPDATE admin_users
                SET password_hash = :password_hash,
                    login_fail_count = 0,
                    locked_until = NULL
                WHERE id = :id
            ");
            $update->execute([
                ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                ':id' => $userId,
            ]);

            writeAuditLog('admin_password_changed', 'Admin password changed: ' . $target['username'], 'success', 'warning', 'admin_user', $userId);
            $message = '관리자 비밀번호를 변경했습니다.';
        } else {
            $role = (string)($_POST['role'] ?? '');
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            if (!array_key_exists($role, $roles)) {
                throw new RuntimeException('존재하지 않는 역할입니다.');
            }

            $wasSuper = ((int)$target['is_active'] === 1 && in_array($target['role'], ['admin', 'super_admin'], true));
            $willSuper = ($isActive === 1 && in_array($role, ['admin', 'super_admin'], true));
            if ($wasSuper && !$willSuper && activeSuperAdminCount() <= 1) {
                throw new RuntimeException('마지막 최고관리자는 비활성화하거나 권한을 낮출 수 없습니다.');
            }
            if ((int)$target['id'] === (int)($_SESSION['admin_user_id'] ?? 0) && $wasSuper && !$willSuper) {
                throw new RuntimeException('자기 자신의 최고관리자 권한은 제거할 수 없습니다.');
            }

            $update = $pdo->prepare("UPDATE admin_users SET role = :role, is_active = :is_active WHERE id = :id");
            $update->execute([':role' => $role, ':is_active' => $isActive, ':id' => $userId]);

            writeAuditLog('admin_user_updated', 'Admin user updated: ' . $target['username'] . ' / role=' . $role . ' / active=' . $isActive, 'success', 'warning', 'admin_user', $userId);
            $message = '관리자 권한을 저장했습니다.';
        }
    } catch (Throwable $e) {
        $status = 'error';
        $message = $e->getMessage();
        writeAuditLog('admin_user_update_failed', 'Admin user update failed: ' . $e->getMessage(), 'failed', 'error', 'admin_user');
    }
}

$users = $pdo->query("SELECT id, username, display_name, role, is_active, last_login_at, login_fail_count, locked_until, created_at FROM admin_users ORDER BY id ASC")->fetchAll();

renderHeader('관리자 계정 관리', 'admin_users');
?>
<div class="admin-dashboard users-page">
    <div class="page-title-section">
        <h1 class="page-main-title">관리자 계정 관리</h1>
        <p class="page-subtitle">관리자별 역할, 활성 상태, 비밀번호를 관리합니다. 마지막 최고관리자 계정은 보호됩니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="notice <?php echo $status === 'error' ? 'notice-danger' : 'notice-success'; ?>"><?php echo h($message); ?></div>
    <?php endif; ?>

    <div class="backup-file-list">
        <?php foreach ($users as $user): ?>
            <article class="backup-file-card admin-user-card">
                <div class="backup-file-main">
                    <strong><?php echo h($user['display_name'] ?: $user['username']); ?></strong>
                    <small>
                        <?php echo h($user['username']); ?>
                        · <?php echo h($roles[$user['role']] ?? $user['role']); ?>
                        · <?php echo $user['is_active'] ? '활성' : '비활성'; ?>
                    </small>
                    <small>
                        마지막 로그인: <?php echo h($user['last_login_at'] ?: '-'); ?>
                        · 실패 <?php echo number_format((int)$user['login_fail_count']); ?>회
                        <?php if (!empty($user['locked_until'])): ?>
                            · 잠금 해제: <?php echo h($user['locked_until']); ?>
                        <?php endif; ?>
                    </small>
                </div>

                <form action="users.php" method="POST" class="backup-form" onsubmit="return confirm('관리자 권한을 변경할까요?');">
                    <?php echo csrfInput(); ?>
                    <input type="hidden" name="action" value="update_role">
                    <input type="hidden" name="user_id" value="<?php echo h($user['id']); ?>">
                    <select name="role" class="form-control">
                        <?php foreach ($roles as $key => $label): ?>
                            <option value="<?php echo h($key); ?>" <?php echo $user['role'] === $key ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <label class="check-card"><input type="checkbox" name="is_active" value="1" <?php echo $user['is_active'] ? 'checked' : ''; ?>> <span>활성 계정</span></label>
                    <button type="submit" class="btn btn-primary btn-sm">권한 저장</button>
                </form>

                <details class="admin-password-panel">
                    <summary>비밀번호 변경</summary>
                    <form action="users.php" method="POST" class="backup-form" autocomplete="off" onsubmit="return confirm('이 관리자 계정의 비밀번호를 변경할까요?');">
                        <?php echo csrfInput(); ?>
                        <input type="hidden" name="action" value="change_password">
                        <input type="hidden" name="user_id" value="<?php echo h($user['id']); ?>">
                        <label class="password-field">
                            <span>새 비밀번호</span>
                            <input type="password" name="password" class="form-control" required minlength="8" autocomplete="new-password">
                        </label>
                        <label class="password-field">
                            <span>새 비밀번호 확인</span>
                            <input type="password" name="password_confirm" class="form-control" required minlength="8" autocomplete="new-password">
                        </label>
                        <button type="submit" class="btn btn-secondary btn-sm">비밀번호 변경</button>
                    </form>
                </details>
            </article>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
