<?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/functions_backup.php';
require_once dirname(__DIR__) . '/includes/admin_notifications.php';
require_once dirname(__DIR__) . '/includes/admin_backup_status.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/layout.php';
requirePermission('backup_view');

$status = $_GET['status'] ?? '';
$message = $_GET['message'] ?? '';

try {
    $backupDir = ensureBackupStorage();
    $dirWritable = is_writable($backupDir);
    $files = listBackupFiles();
} catch (Throwable $e) {
    $backupDir = getBackupDir();
    $dirWritable = false;
    $files = [];
    $status = 'error';
    $message = $message ?: $e->getMessage();
}

$pdo = getDBConnection();
$tableCounts = [];
foreach (backupAllowedTables() as $table) {
    if (!backupTableExists($table)) continue;
    try {
        $tableCounts[$table] = (int)$pdo->query("SELECT COUNT(*) FROM `$table`")->fetchColumn();
    } catch (Throwable $e) {
        $tableCounts[$table] = null;
    }
}

$latest = $files[0] ?? null;
$sections = backupExportSections();
$backupPathLabel = 'storage/backups';
$getId3Installed = class_exists('getID3', false);
$canCreateBackup = hasPermission('backup_create');
$canExportData = hasPermission('export_data');
$canImportData = hasPermission('import_data');
$canRestoreBackup = hasPermission('backup_restore');
$canDownloadBackup = hasPermission('backup_download');
$canDeleteBackup = hasPermission('backup_delete');
$backupStatus = getAdminBackupStatusSummary();
syncAdminBackupStatusNotification($backupStatus);

renderHeader('백업 센터', 'backup');
?>
<div class="settings-page backup-center-page">
    <div class="page-title-section">
        <h1 class="page-main-title">백업 센터</h1>
        <p class="page-subtitle">DB, 설정, 플레이리스트, 태그, 가사, 메모, 별점 데이터를 안전하게 내보내고 검증합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="notice <?php echo $status === 'error' ? 'notice-danger' : 'notice-success'; ?>">
            <?php echo h($message); ?>
        </div>
    <?php endif; ?>

    <section id="backup-status-summary" class="settings-card backup-status-summary status-<?php echo h($backupStatus['status'] ?? 'warning'); ?>">
        <div class="backup-status-summary-head">
            <div>
                <h2>백업 상태 / 복구 준비 상태</h2>
                <p class="settings-muted"><?php echo h($backupStatus['message'] ?? '백업 상태를 확인합니다.'); ?></p>
            </div>
            <span class="diagnostic-state-pill status-<?php echo h($backupStatus['status'] ?? 'warning'); ?>">
                <?php echo h($backupStatus['label'] ?? '주의'); ?>
            </span>
        </div>
        <div class="backup-status-grid">
            <article class="backup-status-card">
                <span>최근 DB 백업</span>
                <strong><?php echo h($backupStatus['latest_at'] ?? '없음'); ?></strong>
                <small><?php echo h($backupStatus['latest']['file_name'] ?? '생성된 DB 백업이 없습니다.'); ?></small>
            </article>
            <article class="backup-status-card">
                <span>성공 / 실패</span>
                <strong><?php echo number_format((int)($backupStatus['valid_count'] ?? 0)); ?> / <?php echo number_format((int)($backupStatus['failed_count'] ?? 0)); ?></strong>
                <small>검증 통과 파일 / 최근 30일 실패 로그</small>
            </article>
            <article class="backup-status-card">
                <span>백업 크기</span>
                <strong><?php echo h($backupStatus['latest_size_text'] ?? '-'); ?></strong>
                <small>전체 <?php echo h($backupStatus['total_size_text'] ?? '0 bytes'); ?></small>
            </article>
            <article class="backup-status-card">
                <span>복구 준비</span>
                <strong><?php echo h($backupStatus['restore_label'] ?? '확인 필요'); ?></strong>
                <small>DB 백업 <?php echo number_format((int)($backupStatus['backup_count'] ?? 0)); ?>개</small>
            </article>
        </div>
        <?php if (!empty($backupStatus['issues'])): ?>
            <ul class="backup-status-issues">
                <?php foreach ($backupStatus['issues'] as $issue): ?>
                    <li><?php echo h($issue); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
        <div class="backup-status-actions">
            <?php if ($canCreateBackup): ?><a class="btn btn-primary" href="#create-backup-form"><i class="fa-solid fa-database"></i> 지금 백업</a><?php endif; ?>
            <a class="btn btn-secondary" href="#backup-file-list"><i class="fa-solid fa-list"></i> 백업 내역</a>
            <?php if ($canRestoreBackup): ?><a class="btn btn-secondary" href="restore.php"><i class="fa-solid fa-rotate-left"></i> 복구 화면</a><?php endif; ?>
        </div>
    </section>

    <div class="backup-summary-grid">
        <div class="backup-summary-card">
            <span>최근 백업</span>
            <strong><?php echo $latest ? h(date('Y-m-d H:i', (int)$latest['modified_at'])) : '없음'; ?></strong>
            <small><?php echo $latest ? h($latest['file_name']) : '아직 생성된 백업이 없습니다.'; ?></small>
        </div>
        <div class="backup-summary-card">
            <span>백업 파일</span>
            <strong><?php echo number_format(count($files)); ?></strong>
            <small>전체 백업 / 선택 export / import 미리보기 포함</small>
        </div>
        <div class="backup-summary-card">
            <span>백업 폴더</span>
            <strong><?php echo $dirWritable ? '쓰기 가능' : '확인 필요'; ?></strong>
            <small><?php echo h($backupPathLabel); ?></small>
        </div>
        <div class="backup-summary-card">
            <span>getID3</span>
            <strong><?php echo $getId3Installed ? '사용 가능' : '미설치'; ?></strong>
            <small><?php echo $getId3Installed ? '내부 태그 분석 가능' : '내부 태그 분석은 제한됩니다.'; ?></small>
        </div>
    </div>

    <div class="backup-two-column">
        <section id="create-backup-form" class="settings-card">
            <div class="settings-card-header"><h2>전체 DB 백업</h2><span class="status-badge ok">안전 작업</span></div>
            <p class="settings-muted">원본 음악 파일은 복사하지 않고 DB와 앱 설정 중심으로 JSON 백업을 생성합니다. 관리자 내부 백업이므로 곡 파일 경로 컬럼도 보존될 수 있습니다.</p>
            <?php if ($canCreateBackup): ?>
            <form action="backup.php" method="POST" class="backup-form">
                <?php echo csrfInput(); ?>
                <label class="form-label" for="backup_note">메모</label>
                <input type="text" id="backup_note" name="note" class="form-control" maxlength="200" placeholder="예: 19차 업데이트 전 백업">
                <button type="submit" class="btn btn-primary">전체 DB 백업 생성</button>
            </form>
            <?php else: ?>
                <p class="settings-muted">현재 계정에는 백업 생성 권한이 없습니다.</p>
            <?php endif; ?>
        </section>

        <section class="settings-card">
            <div class="settings-card-header"><h2>선택 JSON 내보내기</h2><span class="status-badge info">경로 제외</span></div>
            <p class="settings-muted">공유 또는 재가져오기를 위한 선택 export입니다. 곡 메타데이터 export에서는 실제 파일 경로를 제외합니다.</p>
            <?php if ($canExportData): ?>
            <form action="export.php" method="POST" class="backup-form">
                <?php echo csrfInput(); ?>
                <div class="form-grid">
                    <?php foreach ($sections as $key => $section): ?>
                        <label class="check-card">
                            <input type="checkbox" name="sections[]" value="<?php echo h($key); ?>">
                            <span><?php echo h($section['label']); ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
                <label class="form-label" for="export_note">메모</label>
                <input type="text" id="export_note" name="note" class="form-control" maxlength="200">
                <button type="submit" class="btn btn-secondary">선택 데이터 내보내기</button>
            </form>
            <?php else: ?>
                <p class="settings-muted">현재 계정에는 내보내기 권한이 없습니다.</p>
            <?php endif; ?>
        </section>
    </div>

    <div class="backup-two-column">
        <section class="settings-card danger-zone">
            <div class="settings-card-header"><h2>가져오기 미리보기</h2><span class="status-badge warning">검증 먼저</span></div>
            <p class="settings-muted">업로드한 JSON은 먼저 구조와 체크섬을 검사합니다. 적용은 다음 화면에서 선택 병합으로만 진행됩니다.</p>
            <?php if ($canImportData): ?>
            <form action="import.php" method="POST" enctype="multipart/form-data" class="backup-form">
                <?php echo csrfInput(); ?>
                <input type="hidden" name="action" value="preview">
                <input type="file" name="import_file" class="form-control" accept="application/json,.json" required>
                <button type="submit" class="btn btn-primary">가져오기 미리보기</button>
            </form>
            <?php else: ?>
                <p class="settings-muted">현재 계정에는 가져오기 권한이 없습니다.</p>
            <?php endif; ?>
        </section>

        <section class="settings-card danger-zone">
            <div class="settings-card-header"><h2>복원 안내</h2><span class="status-badge danger">위험 작업</span></div>
            <p class="settings-muted">전체 복원은 전체 DB 백업만 허용합니다. 실행 전 현재 DB를 자동 안전 백업하고, 체크섬 검증에 실패하면 복원을 중단합니다.</p>
            <?php if ($canRestoreBackup): ?>
                <a href="restore.php" class="btn btn-danger">전체 복원 화면 열기</a>
            <?php else: ?>
                <p class="settings-muted">현재 계정에는 복원 실행 권한이 없습니다.</p>
            <?php endif; ?>
        </section>
    </div>

    <section class="settings-card">
        <div class="settings-card-header"><h2>주요 테이블 요약</h2><span class="settings-muted"><?php echo number_format(count($tableCounts)); ?>개 테이블</span></div>
        <div class="backup-table-counts">
            <?php foreach ($tableCounts as $table => $count): ?>
                <div><span><?php echo h($table); ?></span><strong><?php echo $count === null ? '오류' : number_format($count); ?></strong></div>
            <?php endforeach; ?>
        </div>
    </section>

    <section id="backup-file-list" class="settings-card">
        <div class="settings-card-header"><h2>백업 파일 목록</h2><span class="settings-muted"><?php echo number_format(count($files)); ?>개</span></div>
        <?php if (empty($files)): ?>
            <p class="empty-text">아직 생성된 백업 파일이 없습니다.</p>
        <?php else: ?>
            <div class="backup-file-list">
                <?php foreach ($files as $file): ?>
                    <article class="backup-file-card">
                        <div class="backup-file-main">
                            <strong title="<?php echo h($file['file_name']); ?>"><?php echo h($file['file_name']); ?></strong>
                            <small><?php echo h(date('Y-m-d H:i:s', (int)$file['modified_at'])); ?> · <?php echo number_format((int)$file['file_size']); ?> bytes</small>
                            <small>종류: <?php echo h($file['export_type'] ?? 'unknown'); ?> · 체크섬: <?php echo !empty($file['checksum']) ? h(substr((string)$file['checksum'], 0, 16)) : '없음'; ?></small>
                        </div>
                        <div class="backup-file-status">
                            <span class="status-badge <?php echo !empty($file['valid']) ? 'ok' : 'danger'; ?>"><?php echo !empty($file['valid']) ? '검증 통과' : '확인 필요'; ?></span>
                            <?php if (!empty($file['errors'])): ?><small><?php echo h(implode(' ', $file['errors'])); ?></small><?php endif; ?>
                        </div>
                        <div class="backup-file-actions">
                            <?php if ($canDownloadBackup): ?>
                            <a href="backup_download.php?file=<?php echo urlencode($file['file_name']); ?>" class="btn btn-secondary btn-sm" data-no-pjax download>다운로드</a>
                            <?php endif; ?>
                            <?php if ($canDeleteBackup): ?>
                            <form action="backup_delete.php" method="POST" onsubmit="return confirm('이 백업 파일을 삭제할까요?');">
                                <?php echo csrfInput(); ?>
                                <input type="hidden" name="backup_file" value="<?php echo h($file['file_name']); ?>">
                                <input type="text" name="confirm_phrase" class="form-control danger-confirm-input" placeholder="삭제합니다" required>
                                <button type="submit" class="btn btn-danger btn-sm">삭제</button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
