<?php
/**
 * api/device/playlist_delete.php — POST /api/device/playlist_delete
 *
 * Elimina una playlist del dispositivo (por MAC). La app la llama cuando el
 * usuario elige "Eliminar" en la tarjeta de la playlist.
 *
 * Request:  { "mac", "playlist_id" }
 * Response: { "ok": true }  o  { "ok": false, "error": "..." }
 */

declare(strict_types=1);

require_once __DIR__ . '/../../lib/helpers.php';
require_once __DIR__ . '/../../lib/device.php';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    json_out(['ok' => false, 'error' => 'method_not_allowed'], 405);
}

$body = read_json_body();

$mac = normalize_mac(isset($body['mac']) ? (string) $body['mac'] : null);
if ($mac === null) {
    json_out(['ok' => false, 'error' => 'mac inválida'], 400);
}

$playlistId = (int) ($body['playlist_id'] ?? 0);
if ($playlistId <= 0) {
    json_out(['ok' => false, 'error' => 'playlist inválida'], 400);
}

try {
    $device = device_find_by_mac($mac);
    if ($device === null) {
        json_out(['ok' => false, 'error' => 'dispositivo no encontrado'], 200);
    }
    db()->prepare('DELETE FROM playlists WHERE id = ? AND device_id = ?')
        ->execute([$playlistId, (int) $device['id']]);

    json_out(['ok' => true], 200);
} catch (Throwable $ex) {
    error_log('[api/device/playlist_delete] ' . $ex->getMessage());
    json_out(['ok' => false, 'error' => 'server_error'], 500);
}
