<?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';

requireAdmin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: auto_playlists.php');
    exit;
}

requireCsrfToken();

$type = preg_replace('/[^a-z0-9_]/', '', (string)($_POST['type'] ?? ''));
$definitions = getAutoPlaylistDefinitions();
if (!isset($definitions[$type])) {
    header('Location: auto_playlists.php');
    exit;
}

$limit = (int)($_POST['limit'] ?? 50);
$limit = max(1, min(100, $limit));
$definition = $definitions[$type];
$name = trim((string)($_POST['name'] ?? ''));
if ($name === '') {
    $name = $definition['title'] . ' ' . date('Y-m-d');
}
$name = function_exists('mb_substr') ? mb_substr($name, 0, 100, 'UTF-8') : substr($name, 0, 100);
$description = '자동 플레이리스트에서 저장됨: ' . $definition['title'];
$songs = getAutoPlaylistSongs($type, $limit);

if (empty($songs)) {
    header('Location: auto_playlist.php?type=' . urlencode($type) . '&status=error&message=' . urlencode('저장할 곡이 없습니다.'));
    exit;
}

try {
    $pdo = getDBConnection();
    $pdo->beginTransaction();

    $baseName = $name;
    $candidateName = $baseName;
    $suffix = 2;
    $nameStmt = $pdo->prepare("SELECT COUNT(*) FROM playlists WHERE name = :name");
    while (true) {
        $nameStmt->execute([':name' => $candidateName]);
        if ((int)$nameStmt->fetchColumn() === 0) break;
        $candidateName = function_exists('mb_substr') ? mb_substr($baseName . ' (' . $suffix . ')', 0, 100, 'UTF-8') : substr($baseName . ' (' . $suffix . ')', 0, 100);
        $suffix++;
    }

    $insertPlaylist = $pdo->prepare("
        INSERT INTO playlists (name, description, created_at, updated_at)
        VALUES (:name, :description, NOW(), NOW())
    ");
    $insertPlaylist->execute([
        ':name' => $candidateName,
        ':description' => $description,
    ]);
    $playlistId = (int)$pdo->lastInsertId();

    $insertSong = $pdo->prepare("
        INSERT INTO playlist_songs (playlist_id, song_id, sort_order)
        VALUES (:playlist_id, :song_id, :sort_order)
    ");
    $seen = [];
    $sortOrder = 1;
    foreach ($songs as $song) {
        $songId = (int)($song['id'] ?? 0);
        if ($songId <= 0 || isset($seen[$songId])) continue;
        $seen[$songId] = true;
        $insertSong->execute([
            ':playlist_id' => $playlistId,
            ':song_id' => $songId,
            ':sort_order' => $sortOrder,
        ]);
        $sortOrder++;
    }

    if ($sortOrder === 1) {
        throw new RuntimeException('저장 가능한 곡이 없습니다.');
    }

    $pdo->commit();
    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'playlist', 'Auto playlist saved as regular playlist', [
            'type' => $type,
            'playlist_id' => $playlistId,
            'song_count' => $sortOrder - 1,
        ]);
    }
    if (function_exists('writeAuditLog')) {
        writeAuditLog('playlist_auto_save', '자동 플레이리스트 저장: ' . $candidateName, 'success', 'info', 'playlist', $playlistId);
    }
    header('Location: playlist_view.php?id=' . $playlistId);
    exit;
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playlist', 'Auto playlist save failed', [
            'type' => $type,
            'error' => $e->getMessage(),
        ]);
    }
    header('Location: auto_playlist.php?type=' . urlencode($type) . '&status=error&message=' . urlencode('플레이리스트 저장에 실패했습니다.'));
    exit;
}
