<?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/feedback.php';

requirePermission('feedback_manage');
ensureFeedbackTable();

$pdo = getDBConnection();
$typeLabels = feedbackTypeLabels();
$statusLabels = feedbackStatusLabels();
$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 = feedbackCleanText($_POST['admin_note'] ?? '', 1000);

        if ($id <= 0) {
            $errors[] = '대상을 찾을 수 없습니다.';
        } elseif (!array_key_exists($status, $statusLabels)) {
            $errors[] = '처리 상태가 올바르지 않습니다.';
        } else {
            try {
                $handledAt = in_array($status, ['completed', 'held'], true) ? date('Y-m-d H:i:s') : null;
                $stmt = $pdo->prepare("
                    UPDATE app_feedback
                    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('feedback_status_update', 'Feedback #' . $id . ' status updated to ' . $status, 'success', 'info', 'feedback', $id);
                header('Location: feedback.php?id=' . $id . '&updated=1');
                exit;
            } catch (Throwable $e) {
                $errors[] = '처리 상태 저장 중 문제가 발생했습니다.';
                if (function_exists('writeAppLog')) {
                    writeAppLog('error', 'feedback_error', 'Feedback status update failed', [
                        'feedback_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[] = 'f.feedback_type = :feedback_type';
    $params[':feedback_type'] = $selectedType;
}
if ($selectedStatus !== '' && array_key_exists($selectedStatus, $statusLabels)) {
    $where[] = 'f.status = :status';
    $params[':status'] = $selectedStatus;
}
if ($query !== '') {
    $where[] = '(f.title LIKE :q_title OR f.body LIKE :q_body OR f.page_url LIKE :q_url)';
    $like = '%' . $query . '%';
    $params[':q_title'] = $like;
    $params[':q_body'] = $like;
    $params[':q_url'] = $like;
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

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

$listSql = "
    SELECT f.id, f.feedback_type, f.status, f.title, f.page_url, f.page_title, f.song_id,
           f.admin_user_id, f.created_at, f.updated_at, s.title AS song_title, s.artist AS song_artist
    FROM app_feedback f
    LEFT JOIN songs s ON s.id = f.song_id
    $whereSql
    ORDER BY f.created_at DESC, f.id DESC
    LIMIT $limit OFFSET $offset
";
$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);
$feedbackRows = $listStmt->fetchAll();

$selectedId = (int)($_GET['id'] ?? 0);
$selectedFeedback = null;
if ($selectedId > 0) {
    $detailStmt = $pdo->prepare("
        SELECT f.*, s.title AS song_title, s.artist AS song_artist
        FROM app_feedback f
        LEFT JOIN songs s ON s.id = f.song_id
        WHERE f.id = :id
    ");
    $detailStmt->execute([':id' => $selectedId]);
    $selectedFeedback = $detailStmt->fetch() ?: null;
}

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

renderHeader('피드백 / 오류 신고 관리', 'feedback');
?>
<div class="admin-dashboard feedback-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="feedback.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($feedbackRows)): ?>
                <p class="empty-text">조건에 맞는 피드백이 없습니다.</p>
            <?php else: ?>
                <div class="feedback-ticket-list">
                    <?php foreach ($feedbackRows as $row): ?>
                        <a class="feedback-ticket <?php echo $selectedId === (int)$row['id'] ? 'active' : ''; ?>" href="<?php echo h(feedbackBuildQuery(['id' => (int)$row['id']])); ?>">
                            <span class="feedback-ticket-meta">
                                <b class="feedback-type-badge type-<?php echo h($row['feedback_type']); ?>"><?php echo h(feedbackTypeLabel($row['feedback_type'])); ?></b>
                                <b class="feedback-status-badge status-<?php echo h($row['status']); ?>"><?php echo h(feedbackStatusLabel($row['status'])); ?></b>
                            </span>
                            <strong><?php echo h($row['title']); ?></strong>
                            <small><?php echo h($row['created_at']); ?><?php echo $row['song_id'] ? ' · 곡 #' . (int)$row['song_id'] : ''; ?></small>
                            <?php if (!empty($row['page_title']) || !empty($row['page_url'])): ?>
                                <span class="feedback-ticket-page"><?php echo h($row['page_title'] ?: $row['page_url']); ?></span>
                            <?php endif; ?>
                        </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(feedbackBuildQuery(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
                        <?php if ($page < $totalPages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(feedbackBuildQuery(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </section>

        <section class="home-section feedback-admin-detail">
            <?php if (!$selectedFeedback): ?>
                <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($selectedFeedback['feedback_type']); ?>"><?php echo h(feedbackTypeLabel($selectedFeedback['feedback_type'])); ?></b>
                            <b class="feedback-status-badge status-<?php echo h($selectedFeedback['status']); ?>"><?php echo h(feedbackStatusLabel($selectedFeedback['status'])); ?></b>
                        </span>
                        <h2><?php echo h($selectedFeedback['title']); ?></h2>
                    </div>
                    <small>#<?php echo (int)$selectedFeedback['id']; ?></small>
                </div>
                <dl class="feedback-detail-meta">
                    <div><dt>등록일</dt><dd><?php echo h($selectedFeedback['created_at']); ?></dd></div>
                    <div><dt>관련 페이지</dt><dd><?php echo h($selectedFeedback['page_title'] ?: '-'); ?><?php echo !empty($selectedFeedback['page_url']) ? ' · ' . h($selectedFeedback['page_url']) : ''; ?></dd></div>
                    <div><dt>관련 곡</dt><dd><?php echo $selectedFeedback['song_id'] ? '#' . (int)$selectedFeedback['song_id'] . ' ' . h(trim(($selectedFeedback['song_title'] ?? '') . ' ' . ($selectedFeedback['song_artist'] ?? ''))) : '-'; ?></dd></div>
                </dl>
                <div class="feedback-body-box">
                    <?php echo nl2br(h($selectedFeedback['body'])); ?>
                </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)$selectedFeedback['id']; ?>">
                    <label>
                        처리 상태
                        <select name="status">
                            <?php foreach ($statusLabels as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo $selectedFeedback['status'] === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>
                        관리자 메모
                        <textarea name="admin_note" rows="4" maxlength="1000" placeholder="처리 내용이나 확인 사항을 남겨주세요."><?php echo h($selectedFeedback['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(); ?>
