<?php
// =============================================================================
// POST /delete — delete a playlist by public_id.
//
// Mapped from:  /playlists/delete, /delete_playlist  (by Glass UrlRewriter)
//
// Inner JSON: { "mac_address": "...", "playlist_id": "1" }  (or "id")
// =============================================================================

require_once __DIR__ . '/includes/client_common.php';

require_method('POST');

$inner = client_decoded_body();
if (!is_array($inner)) {
    json_error('invalid envelope', 400);
}

$mac    = (string)($inner['mac_address'] ?? '');
$device = client_device_by_mac($mac);
if (!$device) {
    client_log_request(null, 'POST', '/delete', client_request_headers(), $inner, 404, ['error' => 'unknown device']);
    json_error('unknown device', 404);
}

// App sends `playlist_id`; older clients / web UI send `id`. Accept either.
$playlist_id = (string)($inner['playlist_id'] ?? $inner['id'] ?? '');
if ($playlist_id === '') {
    json_error('missing playlist id', 400);
}

// Match against public_id first (correct contract). Also accept row PK as a
// fallback for app installs that cached row PKs before the /add fix landed —
// once those clients re-auth they'll get public_ids and this branch stops
// firing. Still scoped to device_id so no cross-device delete is possible.
$n = db_exec(
    'DELETE FROM playlists WHERE device_id = ? AND (public_id = ? OR id = ?)',
    [(int)$device['id'], $playlist_id, (int)$playlist_id]
);

$resp = ['success' => $n > 0, 'deleted' => $n];
client_log_request((int)$device['id'], 'POST', '/delete', client_request_headers(), $inner, 200, $resp);
json_response($resp);
