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

$pdo = getDBConnection();
$filter = isset($_GET['filter']) ? trim((string)$_GET['filter']) : 'all';
$folderKey = isset($_GET['folder']) ? trim((string)$_GET['folder']) : '';
$message = isset($_GET['message']) ? trim((string)$_GET['message']) : '';
$status = isset($_GET['status']) ? trim((string)$_GET['status']) : 'success';

$filters = [
    'all' => ['label' => '전체', 'where' => 's.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0'],
    'artist_missing' => ['label' => '아티스트 없음', 'where' => "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND (s.artist IS NULL OR TRIM(s.artist) = '')"],
    'album_missing' => ['label' => '앨범 없음', 'where' => "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND (s.album IS NULL OR TRIM(s.album) = '')"],
    'genre_missing' => ['label' => '장르 없음', 'where' => "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND (s.genre IS NULL OR TRIM(s.genre) = '')"],
    'year_missing' => ['label' => '연도 없음', 'where' => "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND (s.year IS NULL OR TRIM(s.year) = '')"],
    'recent' => ['label' => '최근 추가', 'where' => 's.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0'],
    'filename' => ['label' => '파일명 분석 사용', 'where' => "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND s.metadata_source IN ('filename', 'mixed')"],
    'manual' => ['label' => '수동 수정됨', 'where' => 's.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND s.is_manual_edited = 1'],
];
if (!isset($filters[$filter])) $filter = 'all';

$where = $filters[$filter]['where'];
$params = [];
if ($folderKey !== '' && preg_match('/^[a-f0-9]{32}$/i', $folderKey)) {
    $where .= " AND MD5(COALESCE(s.folder_path, '')) = :folder_key";
    $params[':folder_key'] = $folderKey;
}
$songs = fetchSongs($where, $params, $filter === 'recent' ? 's.created_at DESC, s.id DESC' : 's.id DESC', 200);

$folderStmt = $pdo->query("
    SELECT MD5(COALESCE(folder_path, '')) AS folder_key,
           COALESCE(NULLIF(folder_name, ''), '폴더 없음') AS folder_name,
           COUNT(*) AS song_count
    FROM songs
    WHERE is_missing = 0 AND COALESCE(is_hidden, 0) = 0
    GROUP BY folder_key, folder_name
    ORDER BY folder_name ASC
    LIMIT 300
");
$folders = $folderStmt->fetchAll();

renderHeader('일괄 수정', 'bulk_edit');
?>
<div class="admin-dashboard bulk-edit-page">
    <div class="page-title-section">
        <h1 class="page-main-title">수동 메타데이터 일괄 수정</h1>
        <p class="page-subtitle">getID3 없이 관리할 때 자주 필요한 아티스트, 앨범, 장르, 연도 값을 선택한 곡에 한 번에 적용합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="alert-box <?php echo $status === 'error' ? 'alert-danger' : 'alert-info'; ?>">
            <div class="alert-icon"><i class="fas fa-circle-info"></i></div>
            <div class="alert-content"><p><?php echo h($message); ?></p></div>
        </div>
    <?php endif; ?>

    <section class="settings-card">
        <form method="GET" class="settings-form compact-filter-form">
            <div class="form-row">
                <div class="form-group">
                    <label for="filter">필터</label>
                    <select name="filter" id="filter">
                        <?php foreach ($filters as $key => $row): ?>
                            <option value="<?php echo h($key); ?>" <?php echo $filter === $key ? 'selected' : ''; ?>><?php echo h($row['label']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="folder">폴더</label>
                    <select name="folder" id="folder">
                        <option value="">전체 폴더</option>
                        <?php foreach ($folders as $folder): ?>
                            <option value="<?php echo h($folder['folder_key']); ?>" <?php echo strcasecmp($folderKey, $folder['folder_key']) === 0 ? 'selected' : ''; ?>>
                                <?php echo h($folder['folder_name']); ?> (<?php echo number_format((int)$folder['song_count']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group form-group-actions">
                    <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-filter"></i> 적용</button>
                </div>
            </div>
        </form>
    </section>

    <form action="bulk_update.php" method="POST" id="bulk-edit-form" onsubmit="return confirm('선택한 곡의 메타데이터를 일괄 수정할까요?');">
        <section class="settings-card bulk-edit-controls">
            <div class="section-heading-row">
                <div>
                    <h2 class="section-title">변경할 값</h2>
                    <p class="settings-muted">입력한 항목만 선택한 곡에 반영됩니다.</p>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group"><label for="artist">아티스트</label><input type="text" id="artist" name="artist" placeholder="비워두면 변경하지 않음"></div>
                <div class="form-group"><label for="album">앨범</label><input type="text" id="album" name="album" placeholder="비워두면 변경하지 않음"></div>
                <div class="form-group"><label for="genre">장르</label><input type="text" id="genre" name="genre" placeholder="비워두면 변경하지 않음"></div>
                <div class="form-group"><label for="year">연도</label><input type="text" id="year" name="year" placeholder="예: 1998"></div>
            </div>
            <div class="bulk-option-row">
                <label class="check-row"><input type="radio" name="manual_action" value="" checked> 수동 보호 상태 유지</label>
                <label class="check-row"><input type="radio" name="manual_action" value="on"> 수동 수정 보호 설정</label>
                <label class="check-row"><input type="radio" name="manual_action" value="off"> 수동 수정 보호 해제</label>
            </div>
            <div class="section-heading-row">
                <p class="settings-muted">값을 입력한 항목만 수정합니다. 메타데이터 값을 바꾸면 자동으로 수동 수정 보호가 켜집니다.</p>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> 선택 곡 일괄 저장</button>
            </div>
        </section>

        <section class="settings-card">
            <div class="section-heading-row">
                <h2 class="section-title">대상 곡 <?php echo number_format(count($songs)); ?>곡</h2>
                <button type="button" class="btn btn-secondary btn-sm" id="bulk-select-toggle">전체 선택</button>
            </div>
            <?php if (empty($songs)): ?>
                <p class="empty-text">조건에 맞는 곡이 없습니다.</p>
            <?php else: ?>
                <div class="table-container bulk-edit-table-container">
                    <table class="data-table bulk-edit-table">
                        <thead><tr><th class="text-center">선택</th><th>곡</th><th>아티스트</th><th>앨범</th><th>장르</th><th>연도</th><th>폴더</th><th>상태</th></tr></thead>
                        <tbody>
                            <?php foreach ($songs as $song): ?>
                                <tr>
                                    <td class="text-center"><input type="checkbox" name="song_ids[]" value="<?php echo h($song['id']); ?>" data-bulk-song-id="<?php echo h($song['id']); ?>" data-bulk-layout="table"></td>
                                    <td><a class="song-title-link" href="../song.php?id=<?php echo h($song['id']); ?>"><?php echo h(metaValue($song['title'], '제목 없음')); ?></a></td>
                                    <td><?php echo h(metaValue($song['artist'], '-')); ?></td>
                                    <td><?php echo h(metaValue($song['album'], '-')); ?></td>
                                    <td><?php echo h(metaValue($song['genre'], '-')); ?></td>
                                    <td><?php echo h(metaValue($song['year'], '-')); ?></td>
                                    <td><?php echo h(metaValue($song['folder_name'] ?? '', '-')); ?></td>
                                    <td>
                                        <?php if (!empty($song['is_manual_edited'])): ?><span class="metadata-badge">수동 보호</span><?php endif; ?>
                                        <?php if (($song['metadata_source'] ?? '') === 'filename'): ?><span class="metadata-badge">파일명</span><?php endif; ?>
                                        <?php if (($song['metadata_source'] ?? '') === 'mixed'): ?><span class="metadata-badge">혼합</span><?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="bulk-edit-card-list">
                    <?php foreach ($songs as $song): ?>
                        <article class="bulk-edit-card">
                            <div class="bulk-edit-card-head">
                                <label class="check-row"><input type="checkbox" name="song_ids[]" value="<?php echo h($song['id']); ?>" data-bulk-song-id="<?php echo h($song['id']); ?>" data-bulk-layout="card"> <strong><?php echo h(metaValue($song['title'], '제목 없음')); ?></strong></label>
                                <a class="btn btn-secondary btn-sm" href="../song_edit.php?id=<?php echo h($song['id']); ?>">개별 수정</a>
                            </div>
                            <div class="bulk-edit-card-meta">
                                <span><b>아티스트</b><?php echo h(metaValue($song['artist'], '-')); ?></span>
                                <span><b>앨범</b><?php echo h(metaValue($song['album'], '-')); ?></span>
                                <span><b>장르</b><?php echo h(metaValue($song['genre'], '-')); ?></span>
                                <span><b>폴더</b><?php echo h(metaValue($song['folder_name'] ?? '', '-')); ?></span>
                            </div>
                            <div class="bulk-edit-card-badges">
                                <?php if (!empty($song['is_manual_edited'])): ?><span class="metadata-badge">수동 보호</span><?php endif; ?>
                                <?php if (($song['metadata_source'] ?? '') === 'filename'): ?><span class="metadata-badge">파일명</span><?php endif; ?>
                                <?php if (($song['metadata_source'] ?? '') === 'mixed'): ?><span class="metadata-badge">혼합</span><?php endif; ?>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    </form>
</div>
<script>
(function initBulkEditPage() {
    const btn = document.getElementById('bulk-select-toggle');
    const form = document.getElementById('bulk-edit-form');
    if (btn && btn.dataset.bulkSelectBound === '1') return;
    if (!btn || !form) return;
    btn.dataset.bulkSelectBound = '1';

    const mobileQuery = window.matchMedia('(max-width: 767px)');
    function currentLayout() {
        return mobileQuery.matches ? 'card' : 'table';
    }
    function getBoxes(layout) {
        return Array.from(form.querySelectorAll('input[name="song_ids[]"][data-bulk-layout="' + layout + '"]'));
    }
    function syncEnabledInputs() {
        const active = currentLayout();
        form.querySelectorAll('input[name="song_ids[]"][data-bulk-layout]').forEach(function (box) {
            box.disabled = box.getAttribute('data-bulk-layout') !== active;
        });
    }
    function syncSameSong(source) {
        const id = source.getAttribute('data-bulk-song-id');
        if (!id) return;
        form.querySelectorAll('input[name="song_ids[]"][data-bulk-song-id]').forEach(function (box) {
            if (box.getAttribute('data-bulk-song-id') !== id) return;
            if (box !== source) box.checked = source.checked;
        });
    }
    form.addEventListener('change', function (event) {
        const box = event.target.closest('input[name="song_ids[]"][data-bulk-song-id]');
        if (box) syncSameSong(box);
    });
    form.addEventListener('submit', syncEnabledInputs);
    if (mobileQuery.addEventListener) {
        mobileQuery.addEventListener('change', syncEnabledInputs);
    } else if (mobileQuery.addListener) {
        mobileQuery.addListener(syncEnabledInputs);
    }
    syncEnabledInputs();

    btn.addEventListener('click', function () {
        syncEnabledInputs();
        const boxes = getBoxes(currentLayout());
        const shouldCheck = boxes.some(box => !box.checked);
        boxes.forEach(box => {
            box.checked = shouldCheck;
            syncSameSong(box);
        });
        btn.textContent = shouldCheck ? '전체 해제' : '전체 선택';
    });
})();
</script>
<?php renderFooter(); ?>
