<?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';
$createdTokenPlain = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();

    try {
        $action = (string)($_POST['action'] ?? '');

        if ($action === 'create') {
            $tokenName = trim((string)($_POST['token_name'] ?? ''));
            $expiresDays = max(0, (int)($_POST['expires_days'] ?? 0));
            if ($tokenName === '' || mb_strlen($tokenName, 'UTF-8') > 120) {
                throw new RuntimeException('토큰 이름은 1~120자로 입력하세요.');
            }

            $createdTokenPlain = 'mlt_' . bin2hex(random_bytes(32));
            $tokenPrefix = substr($createdTokenPlain, 0, 12);
            $expiresAt = $expiresDays > 0 ? date('Y-m-d H:i:s', time() + ($expiresDays * 86400)) : null;

            $stmt = $pdo->prepare("
                INSERT INTO api_tokens (admin_user_id, token_name, token_hash, token_prefix, expires_at)
                VALUES (:admin_user_id, :token_name, :token_hash, :token_prefix, :expires_at)
            ");
            $stmt->execute([
                ':admin_user_id' => (int)($_SESSION['admin_user_id'] ?? 0),
                ':token_name' => $tokenName,
                ':token_hash' => hash('sha256', $createdTokenPlain),
                ':token_prefix' => $tokenPrefix,
                ':expires_at' => $expiresAt,
            ]);

            $tokenId = (int)$pdo->lastInsertId();
            logAdminAction('api_token_created', 'API token created: ' . $tokenName, null);
            writeAuditLog('api_token_created', 'API token created: ' . $tokenName, 'success', 'warning', 'api_token', $tokenId);
            $message = 'API 토큰이 생성되었습니다. 원문 토큰은 이번 한 번만 표시됩니다.';
        } elseif ($action === 'revoke') {
            $tokenId = max(0, (int)($_POST['token_id'] ?? 0));
            if ($tokenId <= 0) {
                throw new RuntimeException('토큰 ID가 올바르지 않습니다.');
            }

            $stmt = $pdo->prepare("
                UPDATE api_tokens
                SET is_active = 0,
                    revoked_at = COALESCE(revoked_at, NOW())
                WHERE id = :id
            ");
            $stmt->execute([':id' => $tokenId]);

            logAdminAction('api_token_revoked', 'API token revoked: #' . $tokenId, null);
            writeAuditLog('api_token_revoked', 'API token revoked: #' . $tokenId, 'success', 'warning', 'api_token', $tokenId);
            $message = 'API 토큰을 폐기했습니다.';
        } else {
            throw new RuntimeException('지원하지 않는 작업입니다.');
        }
    } catch (Throwable $e) {
        $status = 'error';
        $message = $e->getMessage();
        writeAuditLog('api_token_action_failed', 'API token action failed: ' . $e->getMessage(), 'failed', 'error', 'api_token');
    }
}

$tokens = $pdo->query("
    SELECT
        t.id,
        t.token_name,
        t.token_prefix,
        t.last_used_at,
        t.expires_at,
        t.is_active,
        t.created_at,
        t.revoked_at,
        u.username,
        u.display_name
    FROM api_tokens t
    INNER JOIN admin_users u ON u.id = t.admin_user_id
    ORDER BY t.created_at DESC, t.id DESC
    LIMIT 200
")->fetchAll();

renderHeader('API 토큰 관리', 'api_tokens');
?>
<div class="admin-dashboard api-token-page">
    <div class="page-title-section">
        <h1 class="page-main-title">API 토큰 관리</h1>
        <p class="page-subtitle">모바일 앱과 외부 클라이언트 연동용 내부 API 토큰을 관리합니다. 원문 토큰은 저장하지 않고 해시만 보관합니다.</p>
    </div>

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

    <?php if ($createdTokenPlain !== ''): ?>
        <div class="notice notice-warning">
            <strong>새 API 토큰</strong>
            <p>아래 토큰은 지금 한 번만 표시됩니다. 다시 확인할 수 없습니다.</p>
            <code class="api-token-once"><?php echo h($createdTokenPlain); ?></code>
        </div>
    <?php endif; ?>

    <section class="content-card">
        <h2>토큰 생성</h2>
        <form action="api_tokens.php" method="POST" class="backup-form" autocomplete="off">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="action" value="create">
            <label class="password-field">
                <span>토큰 이름</span>
                <input type="text" name="token_name" class="form-control" maxlength="120" required placeholder="예: Android 테스트 앱">
            </label>
            <label class="password-field">
                <span>만료 기간</span>
                <select name="expires_days" class="form-control">
                    <option value="30">30일</option>
                    <option value="90">90일</option>
                    <option value="365">1년</option>
                    <option value="0">만료 없음</option>
                </select>
            </label>
            <button type="submit" class="btn btn-primary">API 토큰 생성</button>
        </form>
    </section>

    <section class="backup-file-list">
        <?php if (empty($tokens)): ?>
            <article class="backup-file-card">
                <div class="backup-file-main">
                    <strong>생성된 API 토큰이 없습니다.</strong>
                    <small>필요할 때만 토큰을 만들고, 사용하지 않는 토큰은 폐기하세요.</small>
                </div>
            </article>
        <?php endif; ?>

        <?php foreach ($tokens as $token): ?>
            <article class="backup-file-card">
                <div class="backup-file-main">
                    <strong><?php echo h($token['token_name']); ?></strong>
                    <small>
                        prefix: <?php echo h($token['token_prefix']); ?>
                        · 소유자: <?php echo h($token['display_name'] ?: $token['username']); ?>
                        · <?php echo (int)$token['is_active'] === 1 ? '활성' : '폐기됨'; ?>
                    </small>
                    <small>
                        생성: <?php echo h($token['created_at']); ?>
                        · 마지막 사용: <?php echo h($token['last_used_at'] ?: '-'); ?>
                        · 만료: <?php echo h($token['expires_at'] ?: '없음'); ?>
                        <?php if (!empty($token['revoked_at'])): ?>
                            · 폐기: <?php echo h($token['revoked_at']); ?>
                        <?php endif; ?>
                    </small>
                </div>

                <?php if ((int)$token['is_active'] === 1): ?>
                    <form action="api_tokens.php" method="POST" class="backup-form" onsubmit="return confirm('이 API 토큰을 폐기할까요? 폐기 후 되돌릴 수 없습니다.');">
                        <?php echo csrfInput(); ?>
                        <input type="hidden" name="action" value="revoke">
                        <input type="hidden" name="token_id" value="<?php echo (int)$token['id']; ?>">
                        <button type="submit" class="btn btn-danger btn-sm">토큰 폐기</button>
                    </form>
                <?php endif; ?>
            </article>
        <?php endforeach; ?>
    </section>
</div>
<?php renderFooter(); ?>
