<?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;
$songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;

if ($playlistId <= 0 || $songId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '요청 값이 올바르지 않습니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = getDBConnection();

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

    $songCheck = $pdo->prepare("SELECT id FROM songs WHERE id = :id AND COALESCE(is_missing, 0) = 0");
    $songCheck->execute([':id' => $songId]);
    if (!$songCheck->fetch()) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => '재생할 수 없는 곡입니다.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $dupCheck = $pdo->prepare("SELECT id FROM playlist_songs WHERE playlist_id = :playlist_id AND song_id = :song_id");
    $dupCheck->execute([':playlist_id' => $playlistId, ':song_id' => $songId]);
    if ($dupCheck->fetch()) {
        http_response_code(409);
        echo json_encode(['success' => false, 'message' => '이미 이 플레이리스트에 있는 곡입니다.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $orderStmt = $pdo->prepare("SELECT COALESCE(MAX(sort_order), 0) + 1 FROM playlist_songs WHERE playlist_id = :playlist_id");
    $orderStmt->execute([':playlist_id' => $playlistId]);
    $nextOrder = (int)$orderStmt->fetchColumn();

    $insertStmt = $pdo->prepare("
        INSERT INTO playlist_songs (playlist_id, song_id, sort_order)
        VALUES (:playlist_id, :song_id, :sort_order)
    ");
    $insertStmt->execute([
        ':playlist_id' => $playlistId,
        ':song_id' => $songId,
        ':sort_order' => $nextOrder,
    ]);

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

    echo json_encode(['success' => true, 'message' => '플레이리스트에 곡을 추가했습니다.'], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playlist_error', 'Playlist add failed', [
            'playlist_id' => $playlistId,
            'song_id' => $songId,
            'error' => $e->getMessage(),
        ]);
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '플레이리스트에 곡을 추가하지 못했습니다.'], JSON_UNESCAPED_UNICODE);
}
