<?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';
require_once dirname(__DIR__) . '/includes/functions_tags.php';
requirePermission('tag_manage');

ensureTagTables();
$pdo = getDBConnection();
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'create') {
            $name = cleanTagName($_POST['name'] ?? '');
            if ($name === '') throw new RuntimeException('태그명을 입력하세요.');
            getOrCreateTag($name);
            $message = '태그를 저장했습니다.';
            if (function_exists('logAdminAction')) logAdminAction('tag_created', 'Tag created: ' . $name);
        } elseif ($action === 'rename') {
            $id = (int)($_POST['tag_id'] ?? 0);
            $name = cleanTagName($_POST['name'] ?? '');
            $normalized = normalizeTagName($name);
            if ($id <= 0 || $name === '' || $normalized === '') throw new RuntimeException('수정할 태그를 확인하세요.');
            $stmt = $pdo->prepare("SELECT id FROM tags WHERE normalized_name = :normalized AND id != :id");
            $stmt->execute([':normalized' => $normalized, ':id' => $id]);
            if ($stmt->fetchColumn()) throw new RuntimeException('같은 이름의 태그가 이미 있습니다. 병합을 사용하세요.');
            $update = $pdo->prepare("UPDATE tags SET name = :name, normalized_name = :normalized WHERE id = :id");
            $update->execute([':name' => $name, ':normalized' => $normalized, ':id' => $id]);
            $message = '태그명을 수정했습니다.';
            if (function_exists('logAdminAction')) logAdminAction('tag_renamed', 'Tag renamed: ' . $name);
        } elseif ($action === 'delete') {
            $id = (int)($_POST['tag_id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('삭제할 태그를 확인하세요.');
            $pdo->beginTransaction();
            $deleteMap = $pdo->prepare("DELETE FROM song_tags WHERE tag_id = :id");
            $deleteMap->execute([':id' => $id]);
            $deleteTag = $pdo->prepare("DELETE FROM tags WHERE id = :id");
            $deleteTag->execute([':id' => $id]);
            $pdo->commit();
            $message = '태그 매핑을 삭제했습니다. 곡은 삭제되지 않았습니다.';
            if (function_exists('logAdminAction')) logAdminAction('tag_deleted', 'Tag deleted: #' . $id);
        } elseif ($action === 'merge') {
            $sourceId = (int)($_POST['source_tag_id'] ?? 0);
            $targetId = (int)($_POST['target_tag_id'] ?? 0);
            if ($sourceId <= 0 || $targetId <= 0 || $sourceId === $targetId) throw new RuntimeException('병합할 태그를 다시 선택하세요.');
            $pdo->beginTransaction();
            $move = $pdo->prepare("
                INSERT IGNORE INTO song_tags (song_id, tag_id)
                SELECT song_id, :target_id FROM song_tags WHERE tag_id = :source_id
            ");
            $move->execute([':target_id' => $targetId, ':source_id' => $sourceId]);
            $deleteMap = $pdo->prepare("DELETE FROM song_tags WHERE tag_id = :source_id");
            $deleteMap->execute([':source_id' => $sourceId]);
            $deleteTag = $pdo->prepare("DELETE FROM tags WHERE id = :source_id");
            $deleteTag->execute([':source_id' => $sourceId]);
            $pdo->commit();
            $message = '태그를 병합했습니다.';
            if (function_exists('logAdminAction')) logAdminAction('tag_merged', 'Tag merged #' . $sourceId . ' to #' . $targetId);
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $error = $e->getMessage();
        if (function_exists('writeAppLog')) writeAppLog('error', 'tag_error', 'Tag manage action failed', ['action' => $action, 'error' => $e->getMessage()]);
    }
}

$tags = $pdo->query("
    SELECT t.id, t.name, t.normalized_name, t.created_at, COUNT(st.id) AS song_count
    FROM tags t
    LEFT JOIN song_tags st ON st.tag_id = t.id
    GROUP BY t.id, t.name, t.normalized_name, t.created_at
    ORDER BY song_count DESC, t.name ASC
")->fetchAll();

renderHeader('태그 관리', 'tag_manage');
?>
<div class="tag-manage-page">
    <div class="page-title-section">
        <h1 class="page-main-title">태그 관리</h1>
        <p class="page-subtitle">분위기, 상황, 시대 같은 사용자 정의 태그를 정리합니다.</p>
    </div>

    <?php if ($message): ?><div class="alert-box alert-success"><div class="alert-content"><?php echo h($message); ?></div></div><?php endif; ?>
    <?php if ($error): ?><div class="alert-box alert-danger"><div class="alert-content"><?php echo h($error); ?></div></div><?php endif; ?>

    <section class="home-section">
        <div class="section-heading-row"><h2 class="section-title">새 태그</h2></div>
        <form method="POST" class="tag-admin-form">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="action" value="create">
            <input type="text" name="name" maxlength="100" placeholder="예: 드라이브, 밤에 듣기">
            <button type="submit" class="btn btn-primary">태그 만들기</button>
        </form>
    </section>

    <section class="home-section">
        <div class="section-heading-row">
            <h2 class="section-title">태그 목록</h2>
            <span class="settings-muted"><?php echo number_format(count($tags)); ?>개</span>
        </div>
        <?php if (empty($tags)): ?>
            <p class="empty-text">아직 등록된 태그가 없습니다.</p>
        <?php else: ?>
            <div class="tag-admin-grid">
                <?php foreach ($tags as $tag): ?>
                    <article class="tag-admin-card">
                        <div>
                            <a class="tag-badge" href="../tag.php?id=<?php echo h($tag['id']); ?>"><?php echo h($tag['name']); ?></a>
                            <p class="settings-muted"><?php echo number_format((int)$tag['song_count']); ?>곡</p>
                        </div>
                        <form method="POST" class="tag-admin-form compact">
                            <?php echo csrfInput(); ?>
                            <input type="hidden" name="action" value="rename">
                            <input type="hidden" name="tag_id" value="<?php echo h($tag['id']); ?>">
                            <input type="text" name="name" value="<?php echo h($tag['name']); ?>" maxlength="100">
                            <button type="submit" class="btn btn-secondary btn-sm">이름 수정</button>
                        </form>
                        <form method="POST" class="tag-admin-form compact" onsubmit="return confirm('이 태그 매핑만 삭제합니다. 곡은 삭제되지 않습니다. 계속할까요?');">
                            <?php echo csrfInput(); ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="tag_id" value="<?php echo h($tag['id']); ?>">
                            <button type="submit" class="btn btn-danger btn-sm">삭제</button>
                        </form>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>

    <?php if (count($tags) >= 2): ?>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">태그 병합</h2></div>
            <form method="POST" class="tag-admin-form" onsubmit="return confirm('원본 태그의 곡 연결을 대상 태그로 옮기고 원본 태그를 삭제합니다. 계속할까요?');">
                <?php echo csrfInput(); ?>
                <input type="hidden" name="action" value="merge">
                <select name="source_tag_id">
                    <?php foreach ($tags as $tag): ?><option value="<?php echo h($tag['id']); ?>"><?php echo h($tag['name']); ?></option><?php endforeach; ?>
                </select>
                <span class="settings-muted">→</span>
                <select name="target_tag_id">
                    <?php foreach ($tags as $tag): ?><option value="<?php echo h($tag['id']); ?>"><?php echo h($tag['name']); ?></option><?php endforeach; ?>
                </select>
                <button type="submit" class="btn btn-primary">병합</button>
            </form>
        </section>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
