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

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

$stmt = $pdo->prepare("
    SELECT id, title, artist, album, genre, duration, extension, play_count, updated_at,
           metadata_updated_at, is_missing, folder_name, relative_path, missing_checked_at, is_hidden
    FROM songs
    WHERE is_missing = 1 AND COALESCE(is_hidden, 0) = 0
    ORDER BY COALESCE(missing_checked_at, updated_at) DESC, id DESC
    LIMIT 300
");
$stmt->execute();
$songs = $stmt->fetchAll();

renderHeader('파일 없음 관리', 'missing_files');
?>
<div class="admin-dashboard missing-files-page">
    <div class="page-title-section">
        <h1 class="page-main-title">파일 없음 관리</h1>
        <p class="page-subtitle">DB에는 남아 있지만 실제 음악 파일을 찾을 수 없는 곡을 확인합니다. 실제 파일 경로는 표시하지 않습니다.</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">
        <div class="section-heading-row">
            <h2 class="section-title">파일 없음 곡 <?php echo number_format(count($songs)); ?>개</h2>
            <a class="btn btn-secondary btn-sm" href="scan.php"><i class="fa-solid fa-rotate"></i> 관리자 스캔으로 이동</a>
        </div>
        <form action="maintenance.php" method="POST" class="inline-action-form" onsubmit="return confirm('파일 없음 상태를 다시 계산할까요?');">
            <button name="action" value="refresh_missing_files" class="btn btn-primary"><i class="fa-solid fa-file-circle-check"></i> 파일 없음 상태 재검사</button>
        </form>
        <p class="settings-muted">삭제는 자동으로 수행하지 않습니다. 상태 해제는 다음 스캔에서 다시 검증될 수 있습니다.</p>
    </section>

    <?php if (empty($songs)): ?>
        <section class="home-section"><p class="empty-text">파일 없음 상태의 곡이 없습니다.</p></section>
    <?php else: ?>
        <div class="table-container missing-table-container">
            <table class="data-table metadata-table">
                <thead>
                    <tr>
                        <th>상태</th>
                        <th>곡</th>
                        <th>아티스트</th>
                        <th>앨범</th>
                        <th>장르</th>
                        <th>폴더</th>
                        <th class="text-center">형식</th>
                        <th class="text-center">마지막 확인</th>
                        <th class="text-center">관리</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($songs as $song): ?>
                        <tr>
                            <td><span class="status-badge-missing">파일 없음</span></td>
                            <td><?php echo h(metaValue($song['title'], '제목 없음')); ?></td>
                            <td><?php echo h(artistName($song['artist'])); ?></td>
                            <td><?php echo h(albumName($song['album'])); ?></td>
                            <td><?php echo h(genreName($song['genre'])); ?></td>
                            <td><?php echo h(metaValue($song['folder_name'] ?? '', '-')); ?></td>
                            <td class="text-center"><span class="file-ext-badge"><?php echo h(strtoupper($song['extension'] ?? '-')); ?></span></td>
                            <td class="text-center"><?php echo h($song['missing_checked_at'] ?: $song['metadata_updated_at'] ?: $song['updated_at'] ?: '-'); ?></td>
                            <td class="text-center">
                                <div class="song-action-group">
                                    <a class="btn btn-secondary btn-sm" href="../song_edit.php?id=<?php echo h($song['id']); ?>">정보 수정</a>
                                    <form action="missing_action.php" method="POST" class="inline-action-form" onsubmit="return confirm('파일 없음 상태를 해제할까요? 다음 스캔에서 다시 확인됩니다.');">
                                        <input type="hidden" name="song_id" value="<?php echo h($song['id']); ?>">
                                        <button name="action" value="clear_missing" class="btn btn-secondary btn-sm">상태 해제</button>
                                    </form>
                                    <form action="missing_action.php" method="POST" class="inline-action-form" onsubmit="return confirm('이 곡을 일반 목록에서 숨길까요?');">
                                        <input type="hidden" name="song_id" value="<?php echo h($song['id']); ?>">
                                        <button name="action" value="hide_song" class="btn btn-danger btn-sm">숨김</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="missing-file-grid">
            <?php foreach ($songs as $song): ?>
                <article class="missing-file-card">
                    <span class="status-badge-missing">파일 없음</span>
                    <strong><?php echo h(metaValue($song['title'], '제목 없음')); ?></strong>
                    <span><?php echo h(artistName($song['artist'])); ?> · <?php echo h(albumName($song['album'])); ?></span>
                    <small>폴더: <?php echo h(metaValue($song['folder_name'] ?? '', '-')); ?></small>
                    <small>확인: <?php echo h($song['missing_checked_at'] ?: $song['metadata_updated_at'] ?: $song['updated_at'] ?: '-'); ?></small>
                    <div class="song-action-group">
                        <a class="btn btn-secondary btn-sm" href="../song_edit.php?id=<?php echo h($song['id']); ?>">정보 수정</a>
                        <form action="missing_action.php" method="POST" class="inline-action-form">
                            <input type="hidden" name="song_id" value="<?php echo h($song['id']); ?>">
                            <button name="action" value="clear_missing" class="btn btn-secondary btn-sm">상태 해제</button>
                        </form>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
