<?php

function musicRequestStatusLabels() {
    return [
        'pending' => '요청 접수대기',
        'in_progress' => '처리중',
        'completed' => '완료',
    ];
}

function musicRequestStatusLabel($status) {
    $labels = musicRequestStatusLabels();
    return $labels[$status] ?? $labels['pending'];
}

function musicRequestNormalizeStatus($status) {
    $status = (string)$status;
    return array_key_exists($status, musicRequestStatusLabels()) ? $status : 'pending';
}

function musicRequestCleanText($value, $limit = 500) {
    $value = trim(ensureUtf8String($value));
    $value = preg_replace('/\s+/u', ' ', $value);
    if (function_exists('mb_substr')) {
        return mb_substr($value, 0, $limit, 'UTF-8');
    }
    return substr($value, 0, $limit);
}

function musicRequestCleanBody($value, $limit = 2000) {
    $value = trim(ensureUtf8String($value));
    $value = str_replace(["\r\n", "\r"], "\n", $value);
    $value = preg_replace("/\n{4,}/u", "\n\n\n", $value);
    if (function_exists('mb_substr')) {
        return mb_substr($value, 0, $limit, 'UTF-8');
    }
    return substr($value, 0, $limit);
}

function ensureMusicRequestsTable() {
    static $ensured = false;
    if ($ensured) return;
    $pdo = getDBConnection();
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS music_requests (
            id INT AUTO_INCREMENT PRIMARY KEY,
            request_title VARCHAR(180) NOT NULL,
            artist VARCHAR(180) DEFAULT NULL,
            album VARCHAR(180) DEFAULT NULL,
            request_body TEXT DEFAULT NULL,
            request_status VARCHAR(30) NOT NULL DEFAULT 'pending',
            requester_admin_id INT DEFAULT NULL,
            admin_note TEXT DEFAULT NULL,
            status_updated_by INT DEFAULT NULL,
            status_updated_at DATETIME DEFAULT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_music_request_status (request_status),
            KEY idx_music_request_created (created_at),
            KEY idx_music_request_requester (requester_admin_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    $ensured = true;
}

function musicRequestCanSubmit($adminUserId, $title, $artist) {
    if (!$adminUserId) return false;
    $stmt = getDBConnection()->prepare("
        SELECT COUNT(*)
        FROM music_requests
        WHERE requester_admin_id = :requester_admin_id
          AND request_title = :request_title
          AND COALESCE(artist, '') = :artist
          AND created_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)
    ");
    $stmt->execute([
        ':requester_admin_id' => $adminUserId,
        ':request_title' => $title,
        ':artist' => $artist,
    ]);
    return (int)$stmt->fetchColumn() === 0;
}
