<?php
// =============================================================================
// POST /add — save a playlist for a device.
//
// Mapped from:  /save_data, /playlists      (by Glass UrlRewriter)
//
// Inner JSON shape (inferred — refine once captured live):
//   { "mac_address": "df:61:22:45:5d:1e",
//     "name":        "My Service",
//     "type":        "xtream"|"m3u",
//     "url":         "http://provider:8080",
//     "username":    "...",       (optional, xtream)
//     "password":    "...",       (optional, xtream)
//     "is_protected": "0"|"1" }
//
// Response: { "success": true, "id": <new public_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', '/add', client_request_headers(), $inner, 404, ['error' => 'unknown device']);
    json_error('unknown device', 404);
}

// The app uses `playlist_*` prefixed keys. Accept the prefixed form first,
// then the bare form as a fallback (older clients / web UI).
$name         = trim((string)($inner['playlist_name'] ?? $inner['name']     ?? ''));
$type         = trim((string)($inner['playlist_type'] ?? $inner['type']     ?? 'xtream'));
$url          = trim((string)($inner['playlist_url']  ?? $inner['url']      ?? ''));
$username     = (string)     ($inner['username']      ?? '');
$password     = (string)     ($inner['password']      ?? '');
$is_protected = (string)     ($inner['is_protected']  ?? '0');

if ($name === '' || $url === '') {
    client_log_request((int)$device['id'], 'POST', '/add', client_request_headers(), $inner, 400, ['error' => 'name+url required']);
    json_error('name and url required', 400);
}

// Allocate the next stable public_id (per-device). Avoid "0" — reserved sentinel.
$rows = db_all('SELECT public_id FROM playlists WHERE device_id = ?', [(int)$device['id']]);
$max = 0;
foreach ($rows as $r) {
    if (ctype_digit((string)$r['public_id'])) {
        $n = (int)$r['public_id'];
        if ($n > $max) { $max = $n; }
    }
}
$public_id = (string)($max + 1);

// If the app didn't pass explicit username/password, parse them from the
// playlist_url query string (Xtream "get.php?username=...&password=..." form).
if ($username === '' || $password === '') {
    $q = parse_url($url, PHP_URL_QUERY);
    if (is_string($q) && $q !== '') {
        $parts = [];
        parse_str($q, $parts);
        if ($username === '' && isset($parts['username'])) { $username = (string)$parts['username']; }
        if ($password === '' && isset($parts['password'])) { $password = (string)$parts['password']; }
    }
}

db_insert(
    'INSERT INTO playlists (device_id, public_id, name, type, url, username, password,
                            is_protected, sort_order)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
    [(int)$device['id'], $public_id, $name, $type, $url, $username, $password,
     $is_protected, $max + 1]
);

// Response `id` MUST be the per-device public_id (not the row PK). /auth also
// hands the app public_id under `id`, and /delete matches on public_id — the
// app caches whichever `id` it last saw, so if /add returned the row PK the
// next /delete would target a public_id that never existed. Symptom is a
// silent "missing playlist id" or "success: false, deleted: 0".
$resp = [
    'success'  => 1,
    'id'       => (int)$public_id,
    'name'     => $name,
    'url'      => $url,
    'mac'      => (string)$device['mac_address'],
    'username' => $username,
    'password' => $password,
];
client_log_request((int)$device['id'], 'POST', '/add', client_request_headers(), $inner, 200, $resp);
json_response($resp);
