<?php
// =============================================================================
// POST /update — update a playlist OR trigger app-update flow.
//
// Mapped from:  /playlists/update, /update_playlist, /apk_link
//               (by Glass UrlRewriter)
//
// Inner JSON shape:
//
//   (Playlist update — /playlists/update, /update_playlist)
//     { "mac_address": "...", "id": "1",
//       "name": "...", "type": "...", "url": "...",
//       "username": "...", "password": "...", "is_protected": "0" }
//
//   (App-update check — /apk_link)
//     { "mac_address": "...", "version": "4.3", "app_type": "phone" }
//     (no "id" field — we return apk_link from config)
//
// We dispatch on presence of "id" vs presence of "version".
// =============================================================================

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', '/update', client_request_headers(), $inner, 404, ['error' => 'unknown device']);
    json_error('unknown device', 404);
}

// ---- Branch 1: playlist update (has "id" field) ----
if (!empty($inner['id'])) {
    $public_id = (string)$inner['id'];
    $row = db_one(
        'SELECT id FROM playlists WHERE device_id = ? AND public_id = ?',
        [(int)$device['id'], $public_id]
    );
    if (!$row) {
        client_log_request((int)$device['id'], 'POST', '/update', client_request_headers(), $inner, 404, ['error' => 'playlist not found']);
        json_error('playlist not found', 404);
    }

    // Accept playlist_* keys (what the app sends) and bare keys (fallback).
    $name         = isset($inner['playlist_name']) ? (string)$inner['playlist_name'] : (isset($inner['name']) ? (string)$inner['name'] : null);
    $type         = isset($inner['playlist_type']) ? (string)$inner['playlist_type'] : (isset($inner['type']) ? (string)$inner['type'] : null);
    $url          = isset($inner['playlist_url'])  ? (string)$inner['playlist_url']  : (isset($inner['url'])  ? (string)$inner['url']  : null);
    $username     = isset($inner['username'])      ? (string)$inner['username']     : null;
    $password     = isset($inner['password'])      ? (string)$inner['password']     : null;
    $is_protected = isset($inner['is_protected'])  ? (string)$inner['is_protected'] : null;

    // Build dynamic update (only set fields that were sent)
    $sets = []; $params = [];
    if ($name !== null)         { $sets[] = 'name = ?';         $params[] = $name; }
    if ($type !== null)         { $sets[] = 'type = ?';         $params[] = $type; }
    if ($url !== null)          { $sets[] = 'url = ?';          $params[] = $url;  }
    if ($username !== null)     { $sets[] = 'username = ?';     $params[] = $username; }
    if ($password !== null)     { $sets[] = 'password = ?';     $params[] = $password; }
    if ($is_protected !== null) { $sets[] = 'is_protected = ?'; $params[] = $is_protected; }
    $sets[] = 'updated_at = ?';  $params[] = unix_now();
    $params[] = (int)$row['id'];

    if (count($sets) > 1) {
        db_exec('UPDATE playlists SET ' . implode(', ', $sets) . ' WHERE id = ?', $params);
    }

    // Match the IBO Ultra wire format: integer 1, no envelope.
    $resp = ['success' => 1, 'id' => (int)$row['id']];
    client_log_request((int)$device['id'], 'POST', '/update', client_request_headers(), $inner, 200, $resp);
    json_response($resp);
}

// ---- Branch 2: app-update / version check (no "id") ----
$cfg  = db_config();
$resp = [
    'success'     => true,
    'app_version' => (string)($cfg['app_version'] ?? '4.3'),
    'apk_link'    => (string)($cfg['apk_link']    ?? ''),
];
client_log_request((int)$device['id'], 'POST', '/update', client_request_headers(), $inner, 200, $resp);
json_response($resp);
