<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/layout.php';
requireAdmin();

$pdo = getDBConnection();
$songId = isset($_GET['id']) ? intval($_GET['id']) : 0;

$stmt = $pdo->prepare("
    SELECT id, title, artist, album, album_artist, genre, year, track_no, disc_no,
           composer, comment, is_manual_edited, metadata_source, metadata_updated_at,
           last_metadata_scan_at, metadata_error, has_cover, cover_mime, is_missing
    FROM songs
    WHERE id = :id
");
$stmt->execute([':id' => $songId]);
$song = $stmt->fetch();

renderHeader('곡 정보 수정', 'song_edit');
?>
<div class="edit-page">
    <div class="page-title-section">
        <h1 class="page-main-title">곡 정보 수정</h1>
        <p class="page-subtitle">실제 파일 경로는 수정하지 않고, 보관함에 표시되는 메타데이터만 수정합니다.</p>
    </div>

    <?php if (!$song): ?>
        <div class="alert-box alert-danger">
            <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="alert-content">
                <h3>곡을 찾을 수 없습니다.</h3>
                <p>존재하지 않는 곡이거나 스캔 목록에서 제외된 항목입니다.</p>
            </div>
        </div>
    <?php else: ?>
        <form action="song_update.php" method="POST" class="metadata-edit-form">
            <input type="hidden" name="id" value="<?php echo h($song['id']); ?>">
            <label>제목<input type="text" name="title" value="<?php echo h($song['title']); ?>" required></label>
            <label>아티스트<input type="text" name="artist" value="<?php echo h($song['artist']); ?>"></label>
            <label>앨범<input type="text" name="album" value="<?php echo h($song['album']); ?>"></label>
            <label>앨범 아티스트<input type="text" name="album_artist" value="<?php echo h($song['album_artist']); ?>"></label>
            <label>장르<input type="text" name="genre" value="<?php echo h($song['genre']); ?>"></label>
            <label>연도<input type="text" name="year" value="<?php echo h($song['year']); ?>" maxlength="10"></label>
            <label>트랙번호<input type="number" name="track_no" value="<?php echo h($song['track_no']); ?>" min="0"></label>
            <label>디스크번호<input type="number" name="disc_no" value="<?php echo h($song['disc_no']); ?>" min="0"></label>
            <label>작곡가<input type="text" name="composer" value="<?php echo h($song['composer']); ?>"></label>
            <label>코멘트<textarea name="comment" rows="4"><?php echo h($song['comment']); ?></textarea></label>

            <div class="metadata-status-panel">
                <strong>메타데이터 상태</strong>
                <span>출처: <?php echo h(metaValue($song['metadata_source'], 'unknown')); ?></span>
                <span>수동 수정 보호: <?php echo !empty($song['is_manual_edited']) ? '켜짐' : '꺼짐'; ?></span>
                <span>마지막 갱신: <?php echo h($song['metadata_updated_at'] ?: '-'); ?></span>
                <span>마지막 스캔: <?php echo h($song['last_metadata_scan_at'] ?: '-'); ?></span>
                <span>앨범아트: <?php echo !empty($song['has_cover']) ? '있음' : '없음'; ?><?php echo !empty($song['cover_mime']) ? ' (' . h($song['cover_mime']) . ')' : ''; ?></span>
                <span>파일 상태: <?php echo !empty($song['is_missing']) ? '파일 없음' : '정상'; ?></span>
                <?php if (!empty($song['metadata_error'])): ?>
                    <p class="metadata-error"><?php echo h($song['metadata_error']); ?></p>
                <?php endif; ?>
            </div>

            <div class="form-actions metadata-protection-actions">
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> 저장</button>
                <a href="song.php?id=<?php echo h($song['id']); ?>" class="btn btn-secondary">취소</a>
            </div>
        </form>

        <form action="admin/metadata_action.php" method="POST" class="maintenance-actions">
            <input type="hidden" name="song_id" value="<?php echo h($song['id']); ?>">
            <button name="action" value="reanalyze_one" class="btn btn-secondary" onclick="return confirm('파일 내부 메타데이터로 다시 읽을까요? 수동 보호가 해제될 수 있습니다.');">파일 내부 메타데이터로 다시 읽기</button>
            <?php if (!empty($song['is_manual_edited'])): ?>
                <button name="action" value="manual_off" class="btn btn-secondary">수동 수정 보호 해제</button>
            <?php else: ?>
                <button name="action" value="manual_on" class="btn btn-secondary">수동 수정 보호 설정</button>
            <?php endif; ?>
        </form>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
