<?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';
require_once dirname(__DIR__) . '/includes/metadata_requests.php';

requirePermission('metadata_request_manage');
ensureMetadataRequestsTable();

$pdo = getDBConnection();
$typeLabels = metadataRequestTypeLabels();
$statusLabels = metadataRequestStatusLabels();
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'update_status') {
        $id = (int)($_POST['id'] ?? 0);
        $status = (string)($_POST['status'] ?? 'received');
        $adminNote = metadataRequestCleanText($_POST['admin_note'] ?? '', 1200);

        if ($id <= 0) {
            $errors[] = '처리할 요청을 찾을 수 없습니다.';
        } elseif (!array_key_exists($status, $statusLabels)) {
            $errors[] = '처리 상태가 올바르지 않습니다.';
        } else {
            try {
                $handledAt = in_array($status, ['applied', 'held', 'rejected'], true) ? date('Y-m-d H:i:s') : null;
                $stmt = $pdo->prepare("
                    UPDATE metadata_correction_requests
                    SET status = :status,
                        admin_note = :admin_note,
                        handled_by_admin = :handled_by_admin,
                        handled_at = :handled_at,
                        updated_at = NOW()
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':status' => $status,
                    ':admin_note' => $adminNote !== '' ? $adminNote : null,
                    ':handled_by_admin' => (int)($_SESSION['admin_user_id'] ?? 0),
                    ':handled_at' => $handledAt,
                    ':id' => $id,
                ]);

                writeAuditLog('metadata_request_status_update', 'Metadata request #' . $id . ' status updated to ' . $status, 'success', 'info', 'metadata_request', $id);
                header('Location: metadata_requests.php?id=' . $id . '&updated=1');
                exit;
            } catch (Throwable $e) {
                $errors[] = '처리 상태 저장 중 문제가 발생했습니다.';
                if (function_exists('writeAppLog')) {
                    writeAppLog('error', 'metadata_request_error', 'Metadata request status update failed', [
                        'request_id' => $id,
                        'error' => limitLogText($e->getMessage(), 300),
                    ]);
                }
            }
        }
    }
}

if (isset($_GET['updated'])) {
    $success = '처리 상태를 저장했습니다.';
}

$selectedType = (string)($_GET['type'] ?? '');
$selectedStatus = (string)($_GET['status'] ?? '');
$query = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 24;
$offset = ($page - 1) * $limit;

$where = [];
$params = [];
if ($selectedType !== '' && array_key_exists($selectedType, $typeLabels)) {
    $where[] = 'r.request_type = :request_type';
    $params[':request_type'] = $selectedType;
}
if ($selectedStatus !== '' && array_key_exists($selectedStatus, $statusLabels)) {
    $where[] = 'r.status = :status';
    $params[':status'] = $selectedStatus;
}
if ($query !== '') {
    $where[] = '(r.current_title LIKE :q_title OR r.current_artist LIKE :q_artist OR r.current_album LIKE :q_album OR r.suggested_value LIKE :q_suggested OR r.reason LIKE :q_reason)';
    $like = '%' . $query . '%';
    $params[':q_title'] = $like;
    $params[':q_artist'] = $like;
    $params[':q_album'] = $like;
    $params[':q_suggested'] = $like;
    $params[':q_reason'] = $like;
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM metadata_correction_requests r $whereSql");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($total / $limit));

$listSql = "
    SELECT r.id, r.song_id, r.request_type, r.status, r.current_title, r.current_artist, r.current_album,
           r.suggested_value, r.created_at, r.updated_at, s.title AS live_title, s.artist AS live_artist
    FROM metadata_correction_requests r
    LEFT JOIN songs s ON s.id = r.song_id
    $whereSql
    ORDER BY r.created_at DESC, r.id DESC
    LIMIT $limit OFFSET $offset
";
$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);
$requestRows = $listStmt->fetchAll();

$selectedId = (int)($_GET['id'] ?? 0);
$selectedRequest = null;
if ($selectedId > 0) {
    $detailStmt = $pdo->prepare("
        SELECT r.*, s.title AS live_title, s.artist AS live_artist, s.album AS live_album, s.genre AS live_genre, s.year AS live_year
        FROM metadata_correction_requests r
        LEFT JOIN songs s ON s.id = r.song_id
        WHERE r.id = :id
        LIMIT 1
    ");
    $detailStmt->execute([':id' => $selectedId]);
    $selectedRequest = $detailStmt->fetch() ?: null;
}

function metadataRequestBuildQuery($overrides = []) {
    $params = array_merge($_GET, $overrides);
    foreach ($params as $key => $value) {
        if ($value === '' || $value === null) unset($params[$key]);
    }
    return 'metadata_requests.php' . ($params ? '?' . http_build_query($params) : '');
}

renderHeader('음악 정보 수정 요청 관리', 'metadata_requests');
?>
<div class="admin-dashboard feedback-admin-page metadata-request-admin-page">
    <div class="page-title-section">
        <h1 class="page-main-title">음악 정보 수정 요청 관리</h1>
        <p class="page-subtitle">사용자가 제보한 제목, 아티스트, 앨범, 장르, 가사, 앨범아트 오류를 확인하고 처리 상태를 관리합니다.</p>
    </div>

    <?php if ($success !== ''): ?><div class="alert success"><?php echo h($success); ?></div><?php endif; ?>
    <?php foreach ($errors as $error): ?><div class="alert error"><?php echo h($error); ?></div><?php endforeach; ?>

    <section class="home-section feedback-admin-filter">
        <form method="get" class="feedback-filter-form">
            <select name="type" aria-label="수정 유형">
                <option value="">모든 유형</option>
                <?php foreach ($typeLabels as $value => $label): ?>
                    <option value="<?php echo h($value); ?>" <?php echo $selectedType === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                <?php endforeach; ?>
            </select>
            <select name="status" aria-label="처리 상태">
                <option value="">모든 상태</option>
                <?php foreach ($statusLabels as $value => $label): ?>
                    <option value="<?php echo h($value); ?>" <?php echo $selectedStatus === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                <?php endforeach; ?>
            </select>
            <input type="search" name="q" value="<?php echo h($query); ?>" placeholder="곡명, 아티스트, 요청 내용 검색">
            <button class="btn btn-primary" type="submit"><i class="fa-solid fa-magnifying-glass"></i> 검색</button>
            <a class="btn btn-secondary" href="metadata_requests.php">초기화</a>
        </form>
        <p class="settings-muted">총 <?php echo number_format($total); ?>건</p>
    </section>

    <div class="feedback-admin-layout">
        <section class="home-section feedback-admin-list">
            <div class="section-heading-row">
                <h2 class="section-title">접수 목록</h2>
                <span class="pill"><?php echo number_format($page); ?> / <?php echo number_format($totalPages); ?>페이지</span>
            </div>
            <?php if (empty($requestRows)): ?>
                <p class="empty-text">조건에 맞는 수정 요청이 없습니다.</p>
            <?php else: ?>
                <div class="feedback-ticket-list">
                    <?php foreach ($requestRows as $row): ?>
                        <a class="feedback-ticket <?php echo $selectedId === (int)$row['id'] ? 'active' : ''; ?>" href="<?php echo h(metadataRequestBuildQuery(['id' => (int)$row['id']])); ?>">
                            <span class="feedback-ticket-meta">
                                <b class="feedback-type-badge type-<?php echo h($row['request_type']); ?>"><?php echo h(metadataRequestTypeLabel($row['request_type'])); ?></b>
                                <b class="feedback-status-badge status-<?php echo h($row['status']); ?>"><?php echo h(metadataRequestStatusLabel($row['status'])); ?></b>
                            </span>
                            <strong><?php echo h($row['current_title'] ?: $row['live_title'] ?: '제목 없음'); ?></strong>
                            <small><?php echo h($row['created_at']); ?> · 곡 #<?php echo (int)$row['song_id']; ?></small>
                            <span class="feedback-ticket-page"><?php echo h($row['current_artist'] ?: $row['live_artist'] ?: '-'); ?><?php echo !empty($row['current_album']) ? ' · ' . h($row['current_album']) : ''; ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>
                <?php if ($totalPages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(metadataRequestBuildQuery(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
                        <?php if ($page < $totalPages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(metadataRequestBuildQuery(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </section>

        <section class="home-section feedback-admin-detail">
            <?php if (!$selectedRequest): ?>
                <p class="empty-text">왼쪽 목록에서 수정 요청을 선택하면 상세 내용을 확인할 수 있습니다.</p>
            <?php else: ?>
                <div class="feedback-detail-head">
                    <div>
                        <span class="feedback-ticket-meta">
                            <b class="feedback-type-badge type-<?php echo h($selectedRequest['request_type']); ?>"><?php echo h(metadataRequestTypeLabel($selectedRequest['request_type'])); ?></b>
                            <b class="feedback-status-badge status-<?php echo h($selectedRequest['status']); ?>"><?php echo h(metadataRequestStatusLabel($selectedRequest['status'])); ?></b>
                        </span>
                        <h2><?php echo h($selectedRequest['current_title'] ?: $selectedRequest['live_title'] ?: '제목 없음'); ?></h2>
                    </div>
                    <small>#<?php echo (int)$selectedRequest['id']; ?></small>
                </div>
                <dl class="feedback-detail-meta">
                    <div><dt>곡 ID</dt><dd>#<?php echo (int)$selectedRequest['song_id']; ?></dd></div>
                    <div><dt>접수일</dt><dd><?php echo h($selectedRequest['created_at']); ?></dd></div>
                    <div><dt>현재 표시</dt><dd><?php echo h(($selectedRequest['live_title'] ?: '-') . ' · ' . ($selectedRequest['live_artist'] ?: '-') . ' · ' . ($selectedRequest['live_album'] ?: '-')); ?></dd></div>
                    <div><dt>접수 당시</dt><dd><?php echo h(($selectedRequest['current_title'] ?: '-') . ' · ' . ($selectedRequest['current_artist'] ?: '-') . ' · ' . ($selectedRequest['current_album'] ?: '-')); ?></dd></div>
                    <div><dt>페이지</dt><dd><?php echo h($selectedRequest['page_url'] ?: '-'); ?></dd></div>
                </dl>
                <div class="metadata-request-detail-grid">
                    <div>
                        <h3>제안 내용</h3>
                        <div class="feedback-body-box"><?php echo nl2br(h($selectedRequest['suggested_value'] ?: '제안 내용 없음')); ?></div>
                    </div>
                    <div>
                        <h3>요청 사유</h3>
                        <div class="feedback-body-box"><?php echo nl2br(h($selectedRequest['reason'] ?: '요청 사유 없음')); ?></div>
                    </div>
                </div>
                <div class="metadata-request-admin-actions">
                    <a class="btn btn-secondary" href="../song.php?id=<?php echo (int)$selectedRequest['song_id']; ?>"><i class="fa-solid fa-circle-info"></i> 곡 상세</a>
                    <a class="btn btn-primary" href="../song_edit.php?id=<?php echo (int)$selectedRequest['song_id']; ?>"><i class="fa-solid fa-pen-to-square"></i> 메타데이터 수정</a>
                </div>
                <form method="post" class="feedback-status-form">
                    <?php echo csrfInput(); ?>
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="id" value="<?php echo (int)$selectedRequest['id']; ?>">
                    <label>
                        처리 상태
                        <select name="status">
                            <?php foreach ($statusLabels as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo $selectedRequest['status'] === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>
                        관리자 메모
                        <textarea name="admin_note" rows="4" maxlength="1200" placeholder="처리 내용이나 확인 사항을 남겨 주세요."><?php echo h($selectedRequest['admin_note'] ?? ''); ?></textarea>
                    </label>
                    <button class="btn btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> 상태 저장</button>
                </form>
            <?php endif; ?>
        </section>
    </div>
</div>
<?php renderFooter(); ?>
