<?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 {
        $userId = max(0, (int)($_POST['user_id'] ?? 0));
        $role = (string)($_POST['role'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        if ($userId <= 0) throw new RuntimeException('관리자 계정이 올바르지 않습니다.');
        if (!array_key_exists($role, $roles)) 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('관리자 계정을 찾을 수 없습니다.');

        $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">
                <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']); ?>회</small>
                </div>
                <form action="users.php" method="POST" class="backup-form" onsubmit="return confirm('관리자 권한을 변경할까요?');">
                    <?php echo csrfInput(); ?>
                    <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>
            </article>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
