<?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';
require_once __DIR__ . '/includes/music_requests.php';

ensureMusicRequestsTable();

$pdo = getDBConnection();
$messages = [];
$errors = [];
$statusLabels = musicRequestStatusLabels();
$selectedStatus = musicRequestNormalizeStatus($_GET['status'] ?? '');
if (!isset($_GET['status']) || $_GET['status'] === '') $selectedStatus = '';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 12;
$offset = ($page - 1) * $perPage;

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

    if ($action === 'create') {
        if (!isLoggedIn()) {
            $errors[] = '로그인 후 음악 요청을 작성할 수 있습니다.';
        } else {
            $title = musicRequestCleanText($_POST['request_title'] ?? '', 180);
            $artist = musicRequestCleanText($_POST['artist'] ?? '', 180);
            $album = musicRequestCleanText($_POST['album'] ?? '', 180);
            $body = musicRequestCleanBody($_POST['request_body'] ?? '', 2000);
            $adminUserId = (int)($_SESSION['admin_user_id'] ?? 0);

            if ($title === '') {
                $errors[] = '요청할 곡명을 입력하세요.';
            } elseif (!musicRequestCanSubmit($adminUserId, $title, $artist)) {
                $errors[] = '같은 음악 요청이 짧은 시간 안에 이미 등록되었습니다.';
            } else {
                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO music_requests
                            (request_title, artist, album, request_body, request_status, requester_admin_id)
                        VALUES
                            (:request_title, :artist, :album, :request_body, 'pending', :requester_admin_id)
                    ");
                    $stmt->execute([
                        ':request_title' => $title,
                        ':artist' => $artist !== '' ? $artist : null,
                        ':album' => $album !== '' ? $album : null,
                        ':request_body' => $body !== '' ? $body : null,
                        ':requester_admin_id' => $adminUserId,
                    ]);
                    $requestId = (int)$pdo->lastInsertId();
                    writeAppLog('info', 'music_request', 'Music request submitted', [
                        'request_id' => $requestId,
                        'title' => $title,
                        'artist' => $artist,
                    ]);
                    $messages[] = '음악 요청을 등록했습니다.';
                    $_POST = [];
                } catch (Throwable $e) {
                    $errors[] = '요청 저장 중 오류가 발생했습니다.';
                    writeAppLog('warning', 'music_request_error', 'Music request submit failed', ['error' => $e->getMessage()]);
                }
            }
        }
    } elseif ($action === 'status') {
        if (!hasPermission('music_scan') && !hasPermission('music_manage')) {
            $errors[] = '요청 상태를 변경할 권한이 없습니다.';
        } else {
            $requestId = max(0, (int)($_POST['request_id'] ?? 0));
            $nextStatus = musicRequestNormalizeStatus($_POST['request_status'] ?? 'pending');
            $adminNote = musicRequestCleanBody($_POST['admin_note'] ?? '', 1000);

            try {
                $stmt = $pdo->prepare("
                    UPDATE music_requests
                    SET request_status = :request_status,
                        admin_note = :admin_note,
                        status_updated_by = :status_updated_by,
                        status_updated_at = NOW()
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':request_status' => $nextStatus,
                    ':admin_note' => $adminNote !== '' ? $adminNote : null,
                    ':status_updated_by' => $_SESSION['admin_user_id'] ?? null,
                    ':id' => $requestId,
                ]);
                if ($stmt->rowCount() > 0) {
                    writeAuditLog('music_request_status_update', '음악 요청 #' . $requestId . ' 상태 변경: ' . musicRequestStatusLabel($nextStatus), 'success', 'info', 'music_request', $requestId);
                    $messages[] = '요청 상태를 변경했습니다.';
                } else {
                    $errors[] = '변경할 요청을 찾지 못했습니다.';
                }
            } catch (Throwable $e) {
                $errors[] = '상태 변경 중 오류가 발생했습니다.';
                writeAppLog('warning', 'music_request_error', 'Music request status update failed', ['request_id' => $requestId, 'error' => $e->getMessage()]);
            }
        }
    }
}

$where = [];
$params = [];
if ($selectedStatus !== '') {
    $where[] = 'r.request_status = :request_status';
    $params[':request_status'] = $selectedStatus;
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

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

$listSql = "
    SELECT r.id, r.request_title, r.artist, r.album, r.request_body, r.request_status,
           r.admin_note, r.created_at, r.updated_at, r.status_updated_at,
           au.display_name, au.username
    FROM music_requests r
    LEFT JOIN admin_users au ON au.id = r.requester_admin_id
    $whereSql
    ORDER BY
        CASE r.request_status WHEN 'pending' THEN 0 WHEN 'in_progress' THEN 1 ELSE 2 END,
        r.created_at DESC
    LIMIT :limit OFFSET :offset
";
$listStmt = $pdo->prepare($listSql);
foreach ($params as $key => $value) {
    $listStmt->bindValue($key, $value);
}
$listStmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$listStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$listStmt->execute();
$requests = $listStmt->fetchAll();

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

$canManageRequests = hasPermission('music_scan') || hasPermission('music_manage');
$loginReturn = 'login.php?return=' . rawurlencode('music_requests.php');

renderHeader('음악 요청 게시판', 'music_requests');
?>
<div class="music-request-page">
    <section class="page-title-section music-request-hero">
        <div>
            <span class="section-kicker">Music Request</span>
            <h1 class="page-main-title">음악 요청 게시판</h1>
            <p class="page-subtitle">추가하고 싶은 음악을 요청하고 처리 상태를 확인합니다. 글쓰기는 로그인 후 가능합니다.</p>
        </div>
        <div class="music-request-counts">
            <span><?php echo number_format($totalRows); ?>건</span>
            <?php if (isLoggedIn()): ?><a class="btn btn-primary" href="#music-request-form"><i class="fa-solid fa-pen"></i> 요청 작성</a><?php endif; ?>
        </div>
    </section>

    <?php foreach ($messages as $message): ?>
        <div class="alert-box alert-success"><div class="alert-icon"><i class="fa-solid fa-circle-check"></i></div><div class="alert-content"><p><?php echo h($message); ?></p></div></div>
    <?php endforeach; ?>
    <?php foreach ($errors as $error): ?>
        <div class="alert-box alert-danger"><div class="alert-icon"><i class="fa-solid fa-triangle-exclamation"></i></div><div class="alert-content"><p><?php echo h($error); ?></p></div></div>
    <?php endforeach; ?>

    <section class="music-request-layout">
        <div class="music-request-main">
            <div class="music-request-filter">
                <a class="<?php echo $selectedStatus === '' ? 'active' : ''; ?>" href="<?php echo h(musicRequestUrl(['status' => '', 'page' => 1])); ?>">전체</a>
                <?php foreach ($statusLabels as $status => $label): ?>
                    <a class="<?php echo $selectedStatus === $status ? 'active' : ''; ?>" href="<?php echo h(musicRequestUrl(['status' => $status, 'page' => 1])); ?>"><?php echo h($label); ?></a>
                <?php endforeach; ?>
            </div>

            <div class="music-request-list">
                <?php if (empty($requests)): ?>
                    <article class="music-request-empty">
                        <i class="fa-regular fa-message"></i>
                        <strong>등록된 음악 요청이 없습니다.</strong>
                        <span>원하는 음악이 있다면 첫 요청을 남겨보세요.</span>
                    </article>
                <?php else: ?>
                    <?php foreach ($requests as $request): ?>
                        <article class="music-request-card status-<?php echo h($request['request_status']); ?>">
                            <div class="music-request-card-head">
                                <span class="music-request-status status-<?php echo h($request['request_status']); ?>"><?php echo h(musicRequestStatusLabel($request['request_status'])); ?></span>
                                <time datetime="<?php echo h($request['created_at']); ?>"><?php echo h($request['created_at']); ?></time>
                            </div>
                            <h2><?php echo h($request['request_title']); ?></h2>
                            <p class="music-request-meta">
                                <?php echo h($request['artist'] ?: '아티스트 미입력'); ?>
                                <?php if (!empty($request['album'])): ?><span>·</span><?php echo h($request['album']); ?><?php endif; ?>
                            </p>
                            <?php if (!empty($request['request_body'])): ?>
                                <p class="music-request-body"><?php echo nl2br(h($request['request_body'])); ?></p>
                            <?php endif; ?>
                            <div class="music-request-foot">
                                <span><i class="fa-regular fa-user"></i> <?php echo h($request['display_name'] ?: $request['username'] ?: '사용자'); ?></span>
                                <?php if (!empty($request['status_updated_at'])): ?><span><i class="fa-solid fa-rotate"></i> <?php echo h($request['status_updated_at']); ?></span><?php endif; ?>
                            </div>
                            <?php if (!empty($request['admin_note'])): ?>
                                <div class="music-request-admin-note">
                                    <strong>관리자 메모</strong>
                                    <p><?php echo nl2br(h($request['admin_note'])); ?></p>
                                </div>
                            <?php endif; ?>
                            <?php if ($canManageRequests): ?>
                                <form method="post" class="music-request-status-form">
                                    <?php echo csrfInput(); ?>
                                    <input type="hidden" name="action" value="status">
                                    <input type="hidden" name="request_id" value="<?php echo h($request['id']); ?>">
                                    <select name="request_status">
                                        <?php foreach ($statusLabels as $status => $label): ?>
                                            <option value="<?php echo h($status); ?>" <?php echo $request['request_status'] === $status ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <input type="text" name="admin_note" value="<?php echo h($request['admin_note'] ?? ''); ?>" placeholder="처리 메모">
                                    <button type="submit" class="btn btn-secondary btn-sm">상태 저장</button>
                                </form>
                            <?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <?php if ($totalPages > 1): ?>
                <div class="pagination music-request-pagination">
                    <?php if ($page > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(musicRequestUrl(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
                    <span><?php echo number_format($page); ?> / <?php echo number_format($totalPages); ?></span>
                    <?php if ($page < $totalPages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(musicRequestUrl(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
                </div>
            <?php endif; ?>
        </div>

        <aside class="music-request-side">
            <?php if (isLoggedIn()): ?>
                <form id="music-request-form" method="post" class="music-request-form">
                    <?php echo csrfInput(); ?>
                    <input type="hidden" name="action" value="create">
                    <div class="music-request-form-head">
                        <i class="fa-solid fa-music"></i>
                        <div>
                            <h2>음악 요청 작성</h2>
                            <p>곡명은 필수입니다. 파일 경로나 개인 정보는 입력하지 마세요.</p>
                        </div>
                    </div>
                    <label>
                        <span>곡명</span>
                        <input type="text" name="request_title" maxlength="180" required value="<?php echo h($_POST['request_title'] ?? ''); ?>" placeholder="예: 좋은 날">
                    </label>
                    <label>
                        <span>아티스트</span>
                        <input type="text" name="artist" maxlength="180" value="<?php echo h($_POST['artist'] ?? ''); ?>" placeholder="예: 아이유">
                    </label>
                    <label>
                        <span>앨범</span>
                        <input type="text" name="album" maxlength="180" value="<?php echo h($_POST['album'] ?? ''); ?>" placeholder="선택 입력">
                    </label>
                    <label>
                        <span>요청 내용</span>
                        <textarea name="request_body" rows="5" maxlength="2000" placeholder="버전, 음원 구분, 요청 사유 등을 적어주세요."><?php echo h($_POST['request_body'] ?? ''); ?></textarea>
                    </label>
                    <button type="submit" class="btn btn-primary"><i class="fa-solid fa-paper-plane"></i> 요청 등록</button>
                </form>
            <?php else: ?>
                <div class="music-request-login-card">
                    <i class="fa-solid fa-lock"></i>
                    <strong>로그인 후 요청할 수 있습니다.</strong>
                    <p>목록은 볼 수 있지만 새 음악 요청 작성은 로그인한 사용자만 가능합니다.</p>
                    <a class="btn btn-primary" href="<?php echo h($loginReturn); ?>">로그인</a>
                </div>
            <?php endif; ?>

            <div class="music-request-guide">
                <strong>상태 안내</strong>
                <p><b>요청 접수대기</b> 관리자가 확인하기 전 상태입니다.</p>
                <p><b>처리중</b> 파일 확보 또는 스캔 반영을 진행 중입니다.</p>
                <p><b>완료</b> 요청 처리가 끝난 상태입니다.</p>
            </div>
        </aside>
    </section>
</div>

<?php renderFooter(); ?>
