<?php
/**
 * api/device/playlist_add.php — POST /api/device/playlist_add
 *
 * Agrega (o actualiza) una playlist del dispositivo (por MAC), como la referencia. La app la llama
 * al "Add Playlist" para que la lista viva EN EL PANEL (fuente de verdad), no sólo local.
 *
 * Request:  { "mac", "name", "type"(xtream|m3u), "url", "username", "password", "playlist_id"(0=nueva) }
 * Response: { "ok": true, "id": <int>, "name": "..." }  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);
}

$url = trim((string) ($body['url'] ?? ''));
if ($url === '') {
    json_out(['ok' => false, 'error' => 'url requerida'], 400);
}
$name     = trim((string) ($body['name'] ?? '')) ?: 'Playlist';
$type     = (string) ($body['type'] ?? 'xtream');
$username = (string) ($body['username'] ?? '');
$password = (string) ($body['password'] ?? '');
$editId   = (int) ($body['playlist_id'] ?? 0);

try {
    $device = device_find_by_mac($mac);
    if ($device === null) {
        json_out(['ok' => false, 'error' => 'dispositivo no encontrado'], 200);
    }
    $deviceId = (int) $device['id'];

    if ($editId > 0) {
        db()->prepare('UPDATE playlists SET name=?, type=?, url=?, username=?, password=? WHERE id=? AND device_id=?')
            ->execute([$name, $type, $url, $username, $password, $editId, $deviceId]);
        $id = $editId;
    } else {
        // Dedup: si ya existe la misma (type+url+username), reusar su id.
        $chk = db()->prepare('SELECT id FROM playlists WHERE device_id=? AND type=? AND url=? AND username=? LIMIT 1');
        $chk->execute([$deviceId, $type, $url, $username]);
        $existing = $chk->fetchColumn();
        if ($existing !== false) {
            $id = (int) $existing;
            db()->prepare('UPDATE playlists SET name=?, password=? WHERE id=?')->execute([$name, $password, $id]);
        } else {
            $sortStmt = db()->prepare('SELECT COALESCE(MAX(sort), -1) + 1 FROM playlists WHERE device_id = ?');
            $sortStmt->execute([$deviceId]);
            $sort = (int) $sortStmt->fetchColumn();
            db()->prepare('INSERT INTO playlists (device_id, name, type, url, username, password, protected, sort) VALUES (?, ?, ?, ?, ?, ?, 0, ?)')
                ->execute([$deviceId, $name, $type, $url, $username, $password, $sort]);
            $id = (int) db()->lastInsertId();
        }
    }

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