<?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';
requirePermission('metadata_bulk_edit');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: bulk_edit.php?status=error&message=' . urlencode('일괄 수정은 POST 방식으로만 실행됩니다.'));
    exit;
}
requireCsrfToken();

try {
    $ids = $_POST['song_ids'] ?? [];
    if (!is_array($ids)) $ids = [];
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), function ($id) {
        return $id > 0;
    })));
    if (empty($ids)) {
        throw new Exception('선택된 곡이 없습니다.');
    }

    $updates = [];
    $params = [];
    $changedMetadata = false;
    foreach (['artist', 'album', 'genre', 'year'] as $column) {
        $value = trim((string)($_POST[$column] ?? ''));
        if ($value !== '') {
            $ph = ':' . $column;
            $updates[] = "`$column` = $ph";
            $params[$ph] = $value;
            $changedMetadata = true;
        }
    }

    $manualAction = (string)($_POST['manual_action'] ?? '');
    if ($changedMetadata) {
        $updates[] = "is_manual_edited = 1";
        $updates[] = "metadata_source = 'manual'";
        $updates[] = "metadata_updated_at = NOW()";
    } elseif ($manualAction === 'on') {
        $updates[] = "is_manual_edited = 1";
    } elseif ($manualAction === 'off') {
        $updates[] = "is_manual_edited = 0";
    }

    if (empty($updates)) {
        throw new Exception('변경할 값이 없습니다.');
    }

    $updates[] = "updated_at = NOW()";
    $idPlaceholders = [];
    foreach ($ids as $index => $id) {
        $ph = ':id' . $index;
        $idPlaceholders[] = $ph;
        $params[$ph] = $id;
    }

    $pdo = getDBConnection();
    $sql = "UPDATE songs SET " . implode(', ', array_unique($updates)) . " WHERE id IN (" . implode(',', $idPlaceholders) . ")";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    logAdminAction('metadata_bulk_update', 'Bulk metadata update: ' . count($ids) . ' selected');

    header('Location: bulk_edit.php?status=success&message=' . urlencode('일괄 수정 완료: ' . $stmt->rowCount() . '곡 반영'));
} catch (Exception $e) {
    header('Location: bulk_edit.php?status=error&message=' . urlencode($e->getMessage()));
}
exit;
