<?php
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '허용되지 않는 요청입니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!verifyCsrfToken()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => '요청 토큰이 올바르지 않습니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$playlistId = isset($_POST['playlist_id']) ? (int)$_POST['playlist_id'] : 0;
$orderRaw = $_POST['order'] ?? '[]';
$order = is_string($orderRaw) ? json_decode($orderRaw, true) : $orderRaw;

if ($playlistId <= 0 || !is_array($order)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '저장할 순서 정보가 올바르지 않습니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$ids = [];
foreach ($order as $value) {
    $id = (int)$value;
    if ($id > 0) {
        $ids[] = $id;
    }
}
$ids = array_values(array_unique($ids));

if (empty($ids)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '저장할 곡이 없습니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

    $playlistCheck = $pdo->prepare("SELECT id FROM playlists WHERE id = :id");
    $playlistCheck->execute([':id' => $playlistId]);
    if (!$playlistCheck->fetch()) {
        $pdo->rollBack();
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => '플레이리스트를 찾을 수 없습니다.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $update = $pdo->prepare("
        UPDATE playlist_songs
        SET sort_order = :sort_order
        WHERE id = :id AND playlist_id = :playlist_id
    ");

    foreach ($ids as $index => $playlistSongId) {
        $update->execute([
            ':sort_order' => $index + 1,
            ':id' => $playlistSongId,
            ':playlist_id' => $playlistId,
        ]);
    }

    $touch = $pdo->prepare("UPDATE playlists SET updated_at = NOW() WHERE id = :id");
    $touch->execute([':id' => $playlistId]);
    $pdo->commit();

    echo json_encode(['success' => true, 'message' => '플레이리스트 순서를 저장했습니다.'], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playlist_error', 'Playlist order update failed', [
            'playlist_id' => $playlistId,
            'error' => $e->getMessage(),
        ]);
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '순서를 저장하지 못했습니다.'], JSON_UNESCAPED_UNICODE);
}
