<?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('name_merge');

$pdo = getDBConnection();
$allowedFields = ['artist' => '아티스트', 'album' => '앨범', 'genre' => '장르'];
$field = (string)($_GET['field'] ?? $_POST['field'] ?? 'artist');
if (!array_key_exists($field, $allowedFields)) $field = 'artist';
$message = '';
$error = '';

function normalizeMergeValue($value) {
    $value = trim(preg_replace('/\s+/u', ' ', (string)$value));
    $value = preg_replace('/[^\p{L}\p{N}]+/u', '', $value);
    return function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $target = trim(preg_replace('/\s+/u', ' ', (string)($_POST['target_value'] ?? '')));
    $sources = $_POST['source_values'] ?? [];
    $includeManual = !empty($_POST['include_manual']);
    if (!is_array($sources)) $sources = [];
    $sources = array_values(array_unique(array_filter(array_map('trim', $sources), static function ($value) {
        return $value !== '';
    })));

    try {
        if ($target === '' || empty($sources)) throw new RuntimeException('기준 이름과 병합할 표기를 선택하세요.');
        $placeholders = [];
        $params = [':target' => $target];
        foreach ($sources as $idx => $source) {
            $key = ':source_' . $idx;
            $placeholders[] = $key;
            $params[$key] = $source;
        }
        $manualClause = $includeManual ? '' : " AND COALESCE(is_manual_edited, 0) = 0";
        $pdo->beginTransaction();
        $sql = "UPDATE songs SET {$field} = :target, is_manual_edited = 1 WHERE {$field} IN (" . implode(',', $placeholders) . ")" . $manualClause;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $affected = $stmt->rowCount();
        $pdo->commit();
        $message = number_format($affected) . '곡의 ' . $allowedFields[$field] . ' 표기를 통합했습니다.';
        if (function_exists('logAdminAction')) logAdminAction('metadata_name_merged', $allowedFields[$field] . ' merged to ' . $target . ' (' . $affected . ')');
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $error = $e->getMessage();
        if (function_exists('writeAppLog')) writeAppLog('error', 'metadata_error', 'Name merge failed', ['field' => $field, 'error' => $e->getMessage()]);
    }
}

$rows = [];
try {
    $stmt = $pdo->query("
        SELECT {$field} AS name, COUNT(*) AS song_count
        FROM songs
        WHERE {$field} IS NOT NULL AND TRIM({$field}) != ''
        GROUP BY {$field}
        ORDER BY {$field} ASC
    ");
    $values = $stmt->fetchAll();
    $groups = [];
    foreach ($values as $row) {
        $key = normalizeMergeValue($row['name']);
        if ($key === '') continue;
        if (!isset($groups[$key])) $groups[$key] = [];
        $groups[$key][] = $row;
    }
    foreach ($groups as $groupRows) {
        if (count($groupRows) > 1) $rows[] = $groupRows;
    }
    usort($rows, static function ($a, $b) {
        $sumA = array_sum(array_map(static fn($row) => (int)$row['song_count'], $a));
        $sumB = array_sum(array_map(static fn($row) => (int)$row['song_count'], $b));
        return $sumB <=> $sumA;
    });
    $rows = array_slice($rows, 0, 30);
} catch (Throwable $e) {
    $rows = [];
    if (function_exists('writeAppLog')) writeAppLog('error', 'db_error', 'Name merge candidates failed', ['field' => $field, 'error' => $e->getMessage()]);
}

renderHeader('표기 통합', 'name_merge');
?>
<div class="name-merge-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="filter-tabs">
            <?php foreach ($allowedFields as $key => $label): ?>
                <a class="filter-tab <?php echo $field === $key ? 'active' : ''; ?>" href="name_merge.php?field=<?php echo h($key); ?>"><?php echo h($label); ?></a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="home-section">
        <div class="section-heading-row">
            <h2 class="section-title"><?php echo h($allowedFields[$field]); ?> 표기 차이 후보</h2>
            <span class="settings-muted"><?php echo number_format(count($rows)); ?>그룹</span>
        </div>
        <?php if (empty($rows)): ?>
            <p class="empty-text">현재 자동으로 찾은 표기 차이 후보가 없습니다.</p>
        <?php else: ?>
            <div class="merge-candidate-list">
                <?php foreach ($rows as $idx => $group): ?>
                    <?php $defaultTarget = $group[0]['name']; ?>
                    <form method="POST" class="merge-candidate-card" onsubmit="return confirm('선택한 표기를 기준 이름으로 통합합니다. 계속할까요?');">
                        <?php echo csrfInput(); ?>
                        <input type="hidden" name="field" value="<?php echo h($field); ?>">
                        <div class="merge-candidate-header">
                            <strong>후보 #<?php echo $idx + 1; ?></strong>
                            <input type="text" name="target_value" value="<?php echo h($defaultTarget); ?>" maxlength="255" aria-label="기준 이름">
                        </div>
                        <div class="merge-source-list">
                            <?php foreach ($group as $row): ?>
                                <label>
                                    <input type="checkbox" name="source_values[]" value="<?php echo h($row['name']); ?>" checked>
                                    <span><?php echo h($row['name']); ?></span>
                                    <small><?php echo number_format((int)$row['song_count']); ?>곡</small>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <label class="merge-manual-toggle">
                            <input type="checkbox" name="include_manual" value="1">
                            수동 수정 보호 곡도 포함
                        </label>
                        <button type="submit" class="btn btn-primary btn-sm">통합 적용</button>
                    </form>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
